让我们考虑这个例子: -
function X(){
var Y = function(arg1,arg2){
document.write(arguments.length);
document.write(arg2);
};
Y(arguments);
}
x(1,2,3,4,5);
/*Outputs 1 and undefined respectively.
Because here i am actually passing an array like-object to Y. */
通过在此处使用申请,我获得了理想的结果。
function X(){
var Y = function(arg1,arg2){
document.write(arguments.length);
document.write(arg2);
};
Y.apply(this,arguments);
}
x(1,2,3,4,5) //outputs 5 and 2
我想创建一个 apply like method ,它接受一个参数Array并通过将参数作为单独的参数值调用来调用该函数。
像:
var arr=[1,2,3,4];
Y.apply_like_method(arr);
//and returns like Y(1,2,3,4)
答案 0 :(得分:1)
鉴于此代码:
var arr=[1,2,3,4];
Y.apply_like_method(arr);
//and returns like Y(1,2,3,4)
要做到这一点:
Function.prototype.apply_like_method = function(args) {
return this.apply(this, args);
}
免责声明:仅供参考。
换句话说,.apply()
无法解决。
答案 1 :(得分:1)
只是为了使用eval的屎和傻笑。
function myApply(fun, ar){
var i, r = [];
for(i=0; i<ar.length; ++i)
r[i] = 'ar['+i+']';
eval('fun('+r.join(',')+');');
}
答案 2 :(得分:0)
您想要使用调用方法。 See the MDN。你所描述的是呼叫方法和应用方法的混合;您希望能够单独提供参数,但是将它们作为数组提供给函数。据我所知,目前还不存在,使用应用/调用会更容易,或者使用javascript对象将params传递给函数。