Gecko and Mozilla Browsers work with this, but why not nodejs?

97 views
Skip to first unread message

Robert Steckroth

unread,
Jul 19, 2015, 4:56:05 PM7/19/15
to nod...@googlegroups.com
I need to override the length property of the Function constructor for a wrapper I am making. Why does the following code work in Gecko and Mazilla browsers but not nodejs?

var f = function(a,b,c) {}
f.length // = 3 <- length is three because 3 parameters are expected by the function

f.__defineGetter__("length", function() { return 5 })
f.length // = 5 <- length is now five because f __proto__.length has been overwritten with a property

The above code works in the latest Chrome and Firefox but not in Nodejs, i wonder why..

Jimb Esser

unread,
Jul 27, 2015, 5:04:57 PM7/27/15
to nodejs, roberts...@gmail.com
If I try this using standard Javascript instead of __defineGetter__, I get a more descriptive error when it fails (in Node only):
> Object.defineProperty(f, 'length', { get: function() { return 5; } });
TypeError: Cannot redefine property: length

And digging deeper:
> Object.getOwnPropertyDescriptor(f, 'length')
{ value: 3,
  writable: false,
  enumerable: false,
  configurable: false }

Looks like the version of V8 Node is using defines length as a non-configurable property.  In Chrome the same function says "configurable: true", so that behavior must have changed.

That being said, anything I've ever used which used the length of a function always causes headaches... various function composition functions, such as .bind will, depending on the version of V8 or Javascript engine (or other 3rd party modules which polyfill over the standard .bind) will often return a misleading result (on older versions of V8, and most polyfills, (function(a,b) {}).bind().length would be 0 instead of 2, since the return function isn't declared with any parameters).

  Jimb Esser

Brandon Moser

unread,
Jul 28, 2015, 9:16:41 AM7/28/15
to nodejs, roberts...@gmail.com
What version of Node.JS are you using? As noted in Jimb's response, Chrome has changed this already. Also, you must remember that Node.JS is built on the Chrome V8 Javascript engine, not the Mozilla/Gecko JS engine. Anything that you do in a Mozilla browser cannot be translated perfectly to NodeJS. 
Reply all
Reply to author
Forward
0 new messages