传递带有参数的函数
Passing a function with parameters
我想将一个带参数的函数传递到另一个函数中,而不需要对其求值。
这种方法不起作用:
function first (id) {...}
function second (func) {
func();
}
second(first(id));
这个方法可以,但我不能使用它,因为参数的数量并不总是相同的:
function first (id) {...}
function second (func, id) {
func(id);
}
second(first, someId);
您可以将#bind
用于部分应用程序:
second( first.bind(null, id) )
创建一个包装函数:
second(function () { first(my, parameters); })
如果您想向函数传递可变数量的参数,可以使用apply,如下所示:
function runit(func, arrayofparam) {
func.apply(this,arrayofparam);
}
所有这些文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply
这个怎么样?
function func1(param1, param2){
console.log("func1");
console.log(param1);
console.log(param2);
}
function func2(param1){
console.log("func2");
console.log(param1);
}
function executor(func, params) {
//This do all the trick :)
func.apply(this, params);
}
executor(func1, ["first", "second"]);
executor(func2, ["lonely"]);
这是一个工作示例:https://jsfiddle.net/xrhkoL5a/(使用浏览器控制台查看结果)。
相关文章:
- 函数参数中的数据与指定变量之间的任何性能差异
- AngularJS:我可以跳过函数参数回调吗
- 为什么不'我们在javascript中使用函数参数的数据类型
- 使用闭包共享构造函数参数
- 函数参数的值错误
- 当一个重要的构造函数参数丢失时应该发生什么
- 阻止ReSharper将JavaScript函数参数放到新行中
- 根据函数参数将CSS值存储在var中,然后对其进行操作
- 使构造函数参数具有ES6类方法的特权
- 当客户端将两个按钮的javascript函数参数修改为相同时,SQL/PHP会更新多行
- Windows.Networking.EndpointPair构造函数参数
- 是否可以使用Sinon.JS检查函数参数绑定是否正确
- 大括号中的Javascript函数参数
- jQuery 无法使用 AJAX 调用访问函数内部的函数参数
- 将JSON字符串转换为函数参数
- eval()读取函数参数有多糟糕
- Javascript不能在一个命令中使用函数参数
- 函数参数在内部不可见,返回新的Promise(函数(resolve,reject).传递给被promise化的函数的
- ES6类构造函数参数
- 是否可以在javascript函数参数列表中调用多个函数