我试图理解 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);
最佳答案
基本上,这是调用构造函数的另一种方法,它使您有机会将构造函数调用包装在另一个函数中。我将重点关注您感到困惑的那一行。 fConstructor
设置为 this
,它引用我们原始的构造函数,在本例中为 MyConstructor
。 fNewConstr
是将覆盖原始构造函数的构造函数。在该 fNewConstr
中,您可以实现 MyConstructor
中未找到的其他代码。在 fNewConstr
中,我们使用函数 apply 调用 fConstructor
方法,将 this
作为上下文传递,并将 aArgs
数组传递给构造方法。然后我们将fNewConstr
的原型(prototype)设置为fConstructor
原型(prototype)来完成继承链。最后,我们返回一个新的fNewConstr
实例。在函数调用前添加 new 关键字会创建一个新对象,将其原型(prototype)设置为函数的原型(prototype),并在新项的上下文中调用该函数。因为我们将 fConstructor
方法与 fNewConstr
的上下文一起应用,所以结果与调用 new MyConstructor()
基本相同。合理?或者我需要更详细地介绍一下吗?
关于使用 apply() 函数的 JavaScript 函数构造函数链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12943073/