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

标签 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 = 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.

最佳答案

基本上,这是调用构造函数的另一种方法,它使您有机会将构造函数调用包装在另一个函数中。我将重点关注您感到困惑的那一行。 fConstructor 设置为 this,它引用我们原始的构造函数,在本例中为 MyConstructorfNewConstr 是将覆盖原始构造函数的构造函数。在该 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/

相关文章:

javascript - 添加 Angular 自定义指令到动态生成的 DOM?

javascript - Divs 占据整个页面

Javascript 创建对象的二维数组

javascript - 有没有办法让一组类方法知道调用何时终止?

javascript - 在不使用 JavaScript 中的 Object.assign(ES6 特性)的情况下从另一个对象扩展

javascript - NodeJS 和 Express 连接外部 API - 有什么有用的工具来管理收到的数据?

javascript - 评估字符串的方法

html - css 中的边距不起作用

html - 垂直对齐 td 中的图像

javascript - 使用 Angular 2 的 http.get() 从本地文件加载 json