views:

131

answers:

1

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 ?

+4  A: 

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 :");
    }
};
Paul Dixon
Try fn.apply(this, arguments);
J-P
have made example more closely match what you are attempting
Paul Dixon
Thanks mate.
subtenante