In general, you cannot pass methods directly to callbacks in Javascript. this bound to the function call point, depending on what form you call, and there is no automatic method binding (for example, there is, for example, Python)
//does not work. var obj = { x: 17, f: function(){ return this.x; } }; //inside doSomething, f forgets its "this" should be obj doSomething( obj.f )
In these cases, you can use Function.prototype.bind (or a similar function from the library of your choice, since bind missing in IE <= 8)
//works (for normal methods - see next bit for console.log in particular) var obj = { x: 17, f: function(){ return this.x; } }; doSomething( obj.f.bind(obj) )
Unfortunately, this is not always enough for console.log. Since this is not an actual function in IE (its evil host object), you cannot use the methods of binding, applying and calling on it in this browser, so the only workaround is returning to the end of the call in an anonymous function.
doSomething( function(x){ return console.log(x); });
Since wrapping console.log in an anonymous function is long and annoying for the type, I usually add the following global function when I develop and debug:
function log(message){ return function(x){ return console.log(message, x); };}; forEach(['asd', 'zxc'], log('->'));
source share