我知道用apply(obj,args)调用带有参数数组的函数的可能性; 有没有办法在创建函数的新实例时使用此功能?
我的意思是这样的:
function A(arg1,arg2){
var a = arg1;
var b = arg2;
}
var a = new A.apply([1,2]); //create new instance using an array of arguments
Run Code Online (Sandbox Code Playgroud)
我希望你明白我的意思...... ^^^
谢谢你的帮助!
解决了!
我得到了正确的答案.为了使答案适合我的问题:
function A(arg1,arg2) {
var a = arg1;
var b = arg2;
}
var a = new (A.bind.apply(A,[A,1,2]))();
Run Code Online (Sandbox Code Playgroud)
Ray*_*nos 15
var wrapper = function(f, args) {
return function() {
f.apply(this, args);
};
};
function Constructor() {
this.foo = 4;
}
var o = new (wrapper(Constructor, [1,2]));
alert(o.foo);
Run Code Online (Sandbox Code Playgroud)
我们接受一个函数和参数,并创建一个函数,将该函数的参数应用于此作用域.
然后,如果你用new关键字调用它,它会传递一个新的this并返回它.
重要的是括号
new (wrapper(Constructor, [1,2]))
在包装器返回的函数上调用new关键字,其中as
new wrapper(Constructor, [1,2])
在包装函数上调用new关键字.
它需要被包装的原因是this你应用它是用new关键字设置的.this需要创建一个新对象并将其传递给一个函数,这意味着您必须.apply(this, array)在函数内部调用.
直播例子
或者,您可以使用ES5 .bind方法
var wrapper = function(f, args) {
var params = [f].concat(args);
return f.bind.apply(f, params);
};
Run Code Online (Sandbox Code Playgroud)
见例子
使用ECMAscript 5,您可以:
function createInstanceWithArguments (fConstructor, aArgs) {
var foo = Object.create(fConstructor.prototype);
fConstructor.apply(foo, aArgs);
return foo;
}
Run Code Online (Sandbox Code Playgroud)
@Raynos的答案很有效,除了非ES5版本在实例化后缺少构造函数的原型.
这是我更新的cApply方法:
var cApply = function(c) {
var ctor = function(args) {
c.apply(this, args);
};
ctor.prototype = c.prototype;
return ctor;
};
Run Code Online (Sandbox Code Playgroud)
哪个可以这样使用:
var WrappedConstructor = cApply(Constructor);
var obj = new WrappedConstructor([1,2,3]);
// or inline like this.
var obj2 = new (cApply(Constructor))([1,2,3]);
Run Code Online (Sandbox Code Playgroud)
JSFiddle供参考.