I’m trying to understand some code Mozilla put out on constructor chaining. I’ve added comments to the parts I think I understand, but I’m still not clear on everything that’s going on here. Can someone explain line by line what is going on in this code?
// Using apply() to chain constructors.
Function.prototype.construct = function (aArgs) {
// What is this line of code doing?
var fConstructor = this, fNewConstr = function () { fConstructor.apply(this, aArgs); };
// Assign the function prototype to the new function constructor's prototype.
fNewConstr.prototype = fConstructor.prototype;
// Return the new function constructor.
return new fNewConstr();
};
// Example usage.
function MyConstructor () {
// Iterate through the arguments passed into the constructor and add them as properties.
for (var nProp = 0; nProp < arguments.length; nProp++) {
this["property" + nProp] = arguments[nProp];
}
}
var myArray = [4, "Hello world!", false];
var myInstance = MyConstructor.construct(myArray);
// alerts "Hello world!"
alert(myInstance.property1);
// alerts "true"
alert(myInstance instanceof MyConstructor);
// alerts "MyConstructor"
alert(myInstance.constructor);
Basically, this is an alternate way to call a constructor function, which gives you the opportunity to wrap the constructor call in another function. I’ll focus on the line you are confused about.
fConstructoris set tothis, which references our original constructor function, in this example that isMyConstructor.fNewConstris the constructor which will override the original constructor. Within thatfNewConstryou could implement additional code not found in theMyConstructor. WithinfNewConstr, we callfConstructorusing the Function apply method, passingthisas the context, and theaArgsarray passed to the construct method. Then we set the prototype of thefNewConstrto thefConstructorprototype to complete the inheritance chain. Finally, we return a new instance offNewConstr. Prefixing the new keyword to a function call creates a new object, sets its prototype to the prototype of the function, and invokes the function in the context of the new item. Because we apply thefConstructormethod with thefNewConstr‘s context, the result is essentially the same as callingnew MyConstructor(). Make sense? Or do I need to go into more detail.