I am looking at the example here Using apply to chain constructors
I understand it except for this line:
fNewConstr.prototype = fConstructor.prototype;
Why is it necessary and why does it not make it lose the function that was just defined for fNewConstr?
Function.prototype.construct = function (aArgs) {
var fConstructor = this, fNewConstr = function () { fConstructor.apply(this, aArgs); };
// Why doesn't fNewConstr.prototype get completely overwritten?
fNewConstr.prototype = fConstructor.prototype;
return new fNewConstr();
};
function MyConstructor () {
for (var nProp = 0; nProp < arguments.length; nProp++) {
this["property" + nProp] = arguments[nProp];
}
}
var myArray = [4, "Hello world!", false];
var myInstance = MyConstructor.construct(myArray);
alert(myInstance.property1); // alerts "Hello world!"
alert(myInstance instanceof MyConstructor); // alerts "true"
alert(myInstance.constructor); // alerts "MyConstructor"
If you mean, why doesn’t
fNewConstr(the function) get overwritten when you write…the answer is because nothing is overwriting it. That code just sets the
prototypeproperty of the function.If your question is: Why doesn’t
fNewConstrget recreated each timeconstructis called, the answer is: It is.