在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
The Answer个
从这里的回复可以清楚地看出,没有内置的方法可以通过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);
}
})();