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

时间:2012-04-03 21:19:02

标签: 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
    });

我要做的是将参数放在给定的匿名函数之外。使用这些参数,您可以执行上述操作。

我知道这段代码不会起作用,因为参数不能在函数本身之外访问。但我想知道是否还有其他办法或解决办法吗?

2 个答案:

答案 0 :(得分:2)

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

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'
});

答案 1 :(得分:0)

Example of function scope

我可能不完全理解你的问题。但是,在JavaScript中,你可以做一些关于功能范围的很酷的东西:

var fruitMixer = function () {
    var arg1 = this.arg1,
        arg2 = this.agr2;
    if (arg1 is something) {

    } else {
        arg2('something else');
    }
}

fruitMixer.call({arg1: 'some val', arg2: function (value) {
        // handle value
    }
})

因此,您可以将上下文this传递给带调用的函数。

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/call