javascript - 将 .apply() 与 'new' 运算符一起使用。这可能吗?

标签 javascript oop class inheritance constructor

在 JavaScript 中,我想创建一个对象实例(通过 new 运算符),但将任意数量的参数传递给构造函数。这可能吗?

我想做的是这样的(但下面的代码不起作用):

function Something(){
    // init stuff
}
function createSomething(){
    return new Something.apply(null, arguments);
}
var s = createSomething(a,b,c); // 's' is an instance of Something
<小时/>

答案

从此处的响应中可以清楚地看出,没有内置方法可以使用 new 运算符调用 .apply()。然而,人们针对这个问题提出了一些非常有趣的解决方案。

我的首选解决方案是 this one from Matthew Crumley (我已对其进行修改以传递 arguments 属性):

var createSomething = (function() {
    function F(args) {
        return Something.apply(this, args);
    }
    F.prototype = Something.prototype;

    return function() {
        return new F(arguments);
    }
})();

最佳答案

使用 ECMAScript5 的 Function.prototype.bind事情变得非常干净:

function newCall(Cls) {
    return new (Function.prototype.bind.apply(Cls, arguments));
    // or even
    // return new (Cls.bind.apply(Cls, arguments));
    // if you know that Cls.bind has not been overwritten
}

它可以按如下方式使用:

var s = newCall(Something, a, b, c);

甚至直接:

var s = new (Function.prototype.bind.call(Something, null, a, b, c));

var s = new (Function.prototype.bind.apply(Something, [null, a, b, c]));

这个和 eval-based solution是唯一始终有效的方法,即使使用像 Date 这样的特殊构造函数:

var date = newCall(Date, 2012, 1);
console.log(date instanceof Date); // true
<小时/>

编辑

一点解释: 我们需要在一个接受有限数量参数的函数上运行 new 。 bind 方法允许我们这样做:

var f = Cls.bind(anything, arg1, arg2, ...);
result = new f();

anything 参数并不重要,因为 new 关键字会重置 f 的上下文。然而,出于语法原因,它是必需的。现在,对于 bind 调用:我们需要传递可变数量的参数,因此这样做可以解决问题:

var f = Cls.bind.apply(Cls, [anything, arg1, arg2, ...]);
result = new f();

让我们将其包装在一个函数中。 Cls 作为参数 0 传递,因此它将是我们的任何内容

function newCall(Cls /*, arg1, arg2, ... */) {
    var f = Cls.bind.apply(Cls, arguments);
    return new f();
}

实际上,根本不需要临时f变量:

function newCall(Cls /*, arg1, arg2, ... */) {
    return new (Cls.bind.apply(Cls, arguments))();
}

最后,我们应该确保 bind 确实是我们所需要的。 (Cls.bind 可能已被覆盖)。因此将其替换为Function.prototype.bind,我们得到如上的最终结果。

关于javascript - 将 .apply() 与 'new' 运算符一起使用。这可能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32548209/

相关文章:

c++ - Linderdaum 引擎中奇怪的多个类名

javascript - 我想使用子值检索 firebase 数据库数据

javascript - jQuery 倒计时在暂停时运行

JavaScript 对象检测

Ruby:创建不可继承的类方法

C++:类型定义和嵌套类问题

javascript - 将值作为参数发送到动态分配的 Controller

javascript - 在 Meteor.js 上开始使用 Hammer.js

c++ - 类的奇怪问题

css - 尝试向 css 添加类属性