Home Ask Login Register

Developers Planet

Your answer is one click away!

Timothy Smith February 2016

How to reference parent parameters of an anonymous function Javascript

I'm trying to figure out how I can reference an argument on a wrapper function stored in a variable that calls an anonymous function. Such as in the example below. The problem I run into is I'm used to accessing parameters via the arguments variable, but that sees only the parameter myFunc. I know it's supposed to be possible, but I can't figure out how.

var myFunc = function(arg1, arg2){//do stuff}
var myFuncWrapped = wrapper(myFunc);

myFuncWrapped('arg value1', 'arg value2');

function wrapper(func){
  //how can I reference 'arg value1' from here since arguments == myFunc?
}

Answers


Ryan February 2016

As the comment suggested, wrapper should be returning a function so you can capture the arguments via closure when myFuncWrapped gets called.

var myFunc = function(arg1, arg2) {
    console.log(arg1); // (For testing only) Should be"arg value1"
};

var myFuncWrapped = wrapper(myFunc);

myFuncWrapped('arg value1', 'arg value2');

function wrapper(func) {
    /* The anonymous function below is actually the one
     * being called when you invoke "myFuncWrapped" so it has the arguments you need.
     */
    return function() {
        console.log(arguments[0]); // (For testing only) Should be"arg value1"
        func.apply(this, arguments);
    }
}

Post Status

Asked in February 2016
Viewed 3,095 times
Voted 12
Answered 1 times

Search




Leave an answer


Quote of the day: live life