[英]Call function.apply from within a returned function does not pass arguments
I need to call a varying number of functions with an arbitrary list of arguments. 我需要使用任意参数列表来调用不同数量的函数。
The general use case is to assign formatting functions to different cells in a generated table. 一般用例是将格式设置功能分配给生成的表中的不同单元。 I need to be able to call multiple formatters but I can only assign one formatting function, hence the multi(). 我需要能够调用多个格式化程序,但是我只能分配一个格式化函数,因此可以指定multi()。
The function returned from multi will be applied as the actual formatter with a set of arguments that need to be passed to each one of the individual formatters. 从multi返回的函数将用作具有一组参数的实际格式化程序,这些参数需要传递给每个单独的格式化程序。
function multi(){
var fns = arguments;
return function(){
var params = arguments;
console.log(params);
_.each(fns, function(fn){
fn.apply(params);
}, this);
};
};
Problem: arguments in 'params' are available inside multi() but are not actually passed to the applied functions. 问题:'params'中的参数在multi()中可用,但实际上并未传递给所应用的函数。 The parameters are available to the console.log() call but are undefined the actual functions. 这些参数可用于console.log()调用,但未定义实际功能。
You can check this bin for an example of this issue: http://jsbin.com/pekomopi/1/edit 您可以检查此垃圾箱以获取此问题的示例: http : //jsbin.com/pekomopi/1/edit
Thanks! 谢谢!
The apply
function takes in two arguments. apply
函数接受两个参数。 The first argument is the this
of the function. 第一个参数是函数的this
。 The second argument is the array of arguments. 第二个参数是参数数组。
All you have to do is change the line to fn.apply(this, params)
. 您所要做的就是将行更改为fn.apply(this, params)
。 With this
being whatever object you want to be the this
of fn
. 有了this
对象,您想成为fn
的this
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.