我试图理解 Mozilla 在构造函数链上发布的一些代码。我已经对我认为我理解的部分添加了评论,但我仍然不清楚这里发生的一切。有人可以逐行解释这段代码中发生了什么吗?
// 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);