In JavaScript, I want to create an object instance (via the new
operator), but pass an arbitrary number of arguments to the constructor.(在JavaScript中,我想创建一个对象实例(通过new
运算符),但是将任意数量的参数传递给构造函数。)
Is this possible?(这可能吗?)
What I want to do is something like this (but the code below does not work):(我想做的是这样的(但是下面的代码不起作用):)
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(答案)
From the responses here, it became clear that there's no built-in way to call .apply()
with the new
operator.(从这里的响应中可以明显看出,没有使用new
运算符调用.apply()
内置方法。) However, people suggested a number of really interesting solutions to the problem.(但是,人们提出了一些非常有趣的解决方案。)
My preferred solution was this one from Matthew Crumley (I've modified it to pass the arguments
property):(我更喜欢的解决方案是Matthew Crumley的解决方案(我已对其进行了修改以传递arguments
属性):)
var createSomething = (function() {
function F(args) {
return Something.apply(this, args);
}
F.prototype = Something.prototype;
return function() {
return new F(arguments);
}
})();
ask by Premasagar translate from so
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…