Javascript 访问给定函数之外的参数

标签 javascript functional-programming arguments anonymous-function

想象一下以下代码:

fruitMixer = function(fruitHandler, action){
    // get the given arguments in fruitHandler
    var args = fruitHandler.arguments;

    // retrieve these arguments outside the fruitHandler function
    if(args[0] == undefined) return;
    var action = args[0]['action'];

    // do something if it wants to mix
    if(action == 'mix'){
        fruitHandler(args);
    }else{
        // do other stuff
    }
}
fruitMixer(function({
    'action': 'mix',
    'apples': 3, 
    'peaches': 5}
    ){
        // mix the fruits
    });

我想做的是获取给定匿名函数之外的参数。使用这些参数,您就可以执行上述操作。

我知道这段代码不起作用,只是因为参数在函数本身之外无法访问。但我想知道是否有其他方法或解决方法可以做到这一点?

最佳答案

显而易见的事情是将处理程序与处理程序参数分开。

fruitMixer = function(fruitHandler, fruitHandlerArgs) {
    //do stuff here

    //call the handler, passing it its args
    fruitHandler(fruitHandlerArgs);
}

fruitMixer(function() {
    //mix the fruits
}, {
    arg1: 'some val',   
    arg2: 'some other val'
});

关于Javascript 访问给定函数之外的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10001549/

相关文章:

javascript - 放大排除链接

javascript - Vue 2.0 中的指令参数属性

syntax - [] 在 Perl 6 中使用匿名函数减少

ios - swift中的嵌套递归函数

linux - 需要一些帮助编写 shell 脚本来添加数字

c - 将变量从c程序作为参数传递给shell脚本

javascript - 切换单个元素的类

javascript - Leaflet Layer Control,从不同文件中抓取 GeoJSON 数据

Java Intstream 获取具有空值的多维数组的索引

python - 将 n 个参数传递给 Python 中的函数