Javascript - 使用参数数组创建实例 [英] Javascript - Create instance with array of arguments
问题描述
我知道用apply(obj,args)调用带有参数数组的函数的可能性;
有没有办法在创建函数的新实例时使用此功能?
I know the possibility to call a function with an array of arguments with apply(obj,args); Is there a way to use this feature when creating a new instance of a function?
我的意思是这样的:
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
我希望你理解我的意思...... ^ ^^
I hope you understand what i mean... ^^^
感谢您的帮助!
解决了!
我得到了正确答案。为了使答案适合我的问题:
I got the right answer. To make the answer fit to my question:
function A(arg1,arg2) {
var a = arg1;
var b = arg2;
}
var a = new (A.bind.apply(A,[A,1,2]))();
推荐答案
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);
我们接受一个函数和参数,并创建一个函数,将该函数的参数应用于此范围。
We take a function and arguments and create a function that applies the arguments to that function with the this scope.
然后,如果你使用new关键字调用它,它将传递一个新的 this
并返回它。
Then if you call it with the new keyword it passes in a new fresh this
and returns it.
重要的是括号
new(包装器(构造函数,[1,2 ]))
在包装器返回的函数上调用new关键字,其中
Calls the new keyword on the function returned from the wrapper, where as
new wrapper(Constructor,[1,2])
在包装器上调用new关键字函数。
Calls the new keyword on the wrapper function.
它需要被包装的原因是你应用它的这个
设置为新关键字。需要创建一个新的这个
对象并传递给一个函数,这意味着你必须调用 .apply(this,array)
在函数内部。
The reason it needs to be wrapped is so that this
that you apply it to is set with the new keyword. A new this
object needs to be created and passed into a function which means that you must call .apply(this, array)
inside a function.
实时示例
或者你可以使用ES5 .bind
方法
Alternatively you could use ES5 .bind
method
var wrapper = function(f, args) {
var params = [f].concat(args);
return f.bind.apply(f, params);
};
参见示例
这篇关于Javascript - 使用参数数组创建实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!