glmxndr
glmxndr

Reputation: 46586

Javascript : accessing function arguments generically

Here is what I have :

var log = function(arg1, arg2){
    console.log("inside :" + arg1 + " / " + arg2);
}; 

var wrap = function(fn){
    return function(args){ 
        console.log("before :");
        fn(args);
        console.log("after :");
    }
};

var fn = new wrap(log);
fn(1,2);

It is wrong, because I'd like to get in the console :

before :
inside :1 / 2
after :

But I get this instead :

before :
inside :1 / undefined
after :

How can I tell javascript that args is all the arguments passed to the function returned by wrap ?

Upvotes: 2

Views: 675

Answers (1)

Paul Dixon
Paul Dixon

Reputation: 300855

You can use apply to call a function with a specified 'this' and argument array, so try

var wrap = function(fn){
    return function(){ 
        console.log("before :");
        fn.apply(this, arguments);
        console.log("after :");
    }
};

Upvotes: 5

Related Questions