在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) 问题是我需要创建传递类的新实例
有没有办法重写这个函数,所以它可以接受任意数量的参数?
function createInstance(ofClass, arg1, arg2, arg3, ..., argN){
return new ofClass(arg1, arg2, arg3, ..., argN);
}
Run Code Online (Sandbox Code Playgroud)
此函数应创建传递的类的实例.例:
var SomeClass = function(arg1, arg2, arg3){
this.someAttr = arg3;
.....
}
SomeClass.prototype.method = function(){}
var instance = createInstance(SomeClass, 'arg1', 'arg2', 'arg3');
Run Code Online (Sandbox Code Playgroud)
所以这应该是真的.
instance instanceof SomeClass == true
Run Code Online (Sandbox Code Playgroud)
现在,我只是将N限制在25,希望很少使用更多的参数.