使用apply()函数的JavaScript函数构造函数链接

使用apply()函数的JavaScript函数构造函数链接,javascript,html,object,constructor,Javascript,Html,Object,Constructor,我试图理解Mozilla在构造函数链接方面的一些代码。我已经对我认为我理解的部分添加了评论,但我仍然不清楚这里发生的一切。有人能逐行解释代码中发生了什么吗 // Using apply() to chain constructors. Function.prototype.construct = function (aArgs) { // What is this line of code doing? var fConstructor = this, fNewConstr =

我试图理解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); 
//对链构造函数使用apply()。
Function.prototype.construct=函数(aArgs){
//这行代码在做什么?
var fConstructor=this,fNewConstr=function(){fConstructor.apply(this,aArgs);};
//将函数原型分配给新函数构造函数的原型。
fNewConstr.prototype=fConstructor.prototype;
//返回新的函数构造函数。
返回新的fNewConstr();
};
//示例用法。
函数MyConstructor(){
//迭代传递到构造函数中的参数,并将它们作为属性添加。
对于(var nProp=0;nProp

基本上,这是调用构造函数的另一种方法,它使您有机会将构造函数调用包装到另一个函数中。我会把重点放在你感到困惑的那一行上
fConstructor
设置为
this
,它引用了我们原来的构造函数,在本例中,它是
MyConstructor
fNewConstr
是将覆盖原始构造函数的构造函数。在该
fNewConstr
中,您可以实现在
MyConstructor
中找不到的其他代码。在
fNewConstr
中,我们使用函数方法调用
fConstructor
,将
this
作为上下文传递,并将
aArgs
数组传递给构造方法。然后我们将
fNewConstr
的原型设置为
fConstructor
原型以完成继承链。最后,我们返回
fNewConstr
的一个新实例。将new关键字作为函数调用的前缀将创建一个新对象,将其原型设置为函数的原型,并在新项的上下文中调用函数。由于我们在
fNewConstr
的上下文中应用了
fConstructor
方法,因此结果基本上与调用
newmyconstructor()
相同。有道理?或者我需要更详细地说明

谢谢你详细的回答。这是有道理的。对于这种类型的构造函数操作,您会使用什么样的场景?对于任何类型的OO继承情况,您都会使用类似的场景。假设您有一个创建动物对象的构造函数,并且希望扩展动物构造函数来创建狗构造函数。您可能希望在Dog构造函数中执行特定于Dog对象的某些任务,但仍然希望将原始动物构造函数应用于对象。这个模式允许您这样做。这似乎与c#实例构造函数非常相似。是的,这与实现类继承的语言中重写构造函数的工作方式非常相似。