【问题标题】:JavaScript Function Constructor Chaining Using The apply() Function使用 apply() 函数的 JavaScript 函数构造函数链接
【发布时间】:2012-10-08 05:28:00
【问题描述】:

我正在尝试理解 Mozilla 在构造函数链上发布的一些代码。我已经在我认为我理解的部分中添加了 cmets,但我仍然不清楚这里发生的一切。有人可以逐行解释这段代码中发生了什么吗?

// 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); 

The original code can be found here.

【问题讨论】:

    标签: javascript html object constructor


    【解决方案1】:

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

    【讨论】:

    • 感谢您的详细解答。这就说得通了。对于这种类型的构造函数操作,您会使用什么样的场景?
    • 对于任何类型的 OO 继承情况,您都会使用类似的东西。假设您有一个创建 Animal 对象的构造函数,并且您想扩展 Animal 构造函数以创建 Dog 构造函数。您可能希望在 Dog 构造函数中执行一些特定于 Dog 对象的任务,但您仍希望将原始 Animal 构造函数应用于对象。这种模式可以让你做到这一点。
    • 这似乎与 c# 实例构造函数非常相似。
    • 是的,这与重写构造函数在实现类继承的语言中的工作方式非常相似。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 2011-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-09
    相关资源
    最近更新 更多