我正在查看此处的示例Using apply to chain constructors
我理解它,除了这一行:
fNewConstr.prototype = fConstructor.prototype;
为什么它是必要的,为什么它不会使它失去刚刚为 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"