Imagine the following code:
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
});
What i'm trying to do is to get the parameters outside of the given anonymous function. With these parameters you then can do things like the above.
I know this code won't work simply because the arguments aren't accessible outside the function itself. But i was wondering if there is another way or workaround to do this?
fruitMixer
is called. Your example is illegal syntax - Zecc 2012-04-03 21:36
The obvious thing to do would be to separate handler from handler arguments.
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'
});
I may not fully understand your question. However, in JavaScript you can do some cool stuff regarding function scope:
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
}
})
So you can pass the context this
into a function with call.
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/call