javascript - issue with using .apply on functions

javascript

Solution

Try

for (var m in namespace) { 
   if ( namespace.hasOwnProperty(m) && (typeof namespace[m]=='function') ) {
      logger[m] = namespace[m];
      (function(index){
         namespace[index] = function() {
           logger._callback(arguments);
           logger[index].apply(this, arguments);
         };
      })(m);
   }
}

otherwise the `namespace[m] = function(){}` will use whatever m is last

Problem

Okay so I have an object and I want to apply a callback function to all of the methods in the object. This is what I have tried so far: ``` var namespace = { foo : 'bar', foobar : function() { console.log('call from foobar!')}, someFunc : function() { console.log('call from someFunc!')}, someFunc2 : function() { console.log('call from someFunc2!')} } var logger = { _callback : function () { console.log('call from logger!',arguments); } } for (var m in namespace) { if ( namespace.hasOwnProperty(m) && (typeof namespace[m]=='function') ) { logger[m] = namespace[m]; namespace[m] = function() { logger._callback(arguments); logger[m].apply(this, arguments); } } } namespace.foobar('foo'); namespace.someFunc('bar'); namespace.someFunc2('bar2'); ``` This is what is getting logged to the console: ``` call from logger! [["foo"]] call from someFunc2! call from logger! [["bar"]] call from someFunc2! call from logger! [["bar2"]] call from someFunc2! ``` As you can see, for some reason all 3 methods of `namespace` are outputting `'call from someFunc2!` which is wrong. I'm not sure what the issue here is.. what am I doing wrong?

Original source

Related problems