Javascript access parameters outside of a given function

Go To StackoverFlow.com

2

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?

2012-04-03 21:19
by sebas2day
seems a valid question of pattern to me - NoName 2012-04-03 21:29
But... if you're giving the anonymous function parameters, then you're calling it. It should have run and returned... whatever... by the time fruitMixer is called. Your example is illegal syntax - Zecc 2012-04-03 21:36
I know the syntax is illigal, i was just wondering if accessing these parameters is possible (what i guess it won't) but i like to see some creative solutions trying to do the same thin - sebas2day 2012-04-03 21:52
Wait... are you trying to implement the Chain-of-Responsability pattern, by any chance? Here's an example I find after a quick search: http://www.joezimjs.com/javascript/javascript-design-patterns-chain-of-responsibility - Zecc 2012-04-03 21:48


2

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'
});
2012-04-03 21:28
by NoName


0

Example of function scope

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

2012-04-03 21:34
by Joe
Ads