2

想象一下下面的代码:

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

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

我知道这段代码不能正常工作,因为在函数本身之外无法访问参数。但我想知道是否有另一种方法或解决方法可以做到这一点?

4

2 回答 2

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'
});
于 2012-04-03T21:28:46.967 回答
0

功能范围示例

我可能不完全理解你的问题。但是,在 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

于 2012-04-03T21:34:51.250 回答