Object-oriented JavaScript
constructor arguments

There are special techniques for passing argument lists back through the chain of constructors, when creating JavaScript objects.

JavaScript functions have methods apply and call, just for this purpose.

Furthermore, during the execution of a JavaScript function, a local variable named arguments exists to hold the values of the arguments passed to the function.

example: passing back argument lists that grow linearly

The technique is easiest in situations where each constructor’s arguments are just the parents arguments, with more arguments appended, as in this example:



Now gc and its ancestors are initialized from the argument list provided to operator new:

more complicated parent arguments

There are situations in which it is inconvenient for the arguments of the child constructors to be simple augmentations of the parent constructor arguments. In such situations, there are a couple of options for calling a parent constructor.

One is to manipulate the arguments object and passing it to apply as above. The other is to pass argument directly with the constructor function’s call method.

The second option is easiest. The call method takes a variable-length list of arguments. The first is the current object, the others are the arguments to pass to the function.

One would expect that arguments was a plain JavaScript Array, so that all the Array manipulation functions could be used with it. But it isn’t—it is, according to the JavaScript 1.5 manual, “an array-like object”.

ECMA-262 refers to it as a separate kind of thing, an “arguments object”, and says it has member length and that its elements can be accessed with the bracket operator. The only place where I find that the Array type and arguments object meet in ECMA-262 is where apply takes either an Array or an arguments object.

There seem to be two options for manipulating arguments.

The most obvious is to write your own code to explicitly loop over the elements to create a custom Array.

Another, advocated in Correct OOP for Javascript, is to pass the arguments to Array functions via call, e.g.

	Array.prototype.slice.call( arguments, 1 )

This seems to work, but I don’t understand why, nor do I know if it’s standard. It appears to rely on Array internal implementation. The following obfuscation is also seen occasionally:

	[].slice.call( arguments, 1 )

Also note: in JavaScript 1.3 and earlier, arguments was also a property of Function.

See

JavaScript 1.5 Reference:Global Objects:Function:apply

JavaScript 1.5 Reference:Functions:arguments

ECMA-262

Javascript Closures

JavaScript Closures for Dummies by Morris Johns