在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
Run Code Online (Sandbox Code Playgroud)
答案
从这里的回复中可以清楚地看出,没有内置的方式.apply()与new运营商通话.然而,人们提出了一些非常有趣的解决方案.
我首选的解决方案是Matthew Crumley的这个解决方案(我已将其修改为通过该arguments属性):
var createSomething = (function() {
function F(args) {
return Something.apply(this, args);
}
F.prototype = Something.prototype;
return function() {
return new F(arguments);
}
})();
Run Code Online (Sandbox Code Playgroud) 我正在寻找一个可调用的JavaScript对象,具有任意原型链,但不修改Function.prototype.
换句话说,这必须工作:
var o = { x: 5 };
var foo = bar(o);
assert(foo() === "Hello World!");
delete foo.x;
assert(foo.x === 5);
Run Code Online (Sandbox Code Playgroud)
没有做任何全球变化.