Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><strong>In general you can't pass methods directly to callbacks in Javascript.</strong> The <code>this</code> is bound at the point of the function call, depending on what form you call it and there is no automatic binding of methods (like there is in, for example, Python)</p> <pre><code>//does not work. var obj = { x: 17, f: function(){ return this.x; } }; //inside doSomething, f forgets its "this" should be obj doSomething( obj.f ) </code></pre> <p>In these cases, one might use <code>Function.prototype.bind</code> (or a similar function from your library of choice, since <code>bind</code> is not present in IE &lt;= 8)</p> <pre><code>//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) ) </code></pre> <p><strong>Unfortunately, however, this is not always enough for console.log.</strong> Since it is not an actual Function in IE, (its an evil host object) you cannot use bind, apply and call methods on it on that browser so the only workaround is falling back to wrapping the call in an anonymous function</p> <pre><code>doSomething( function(x){ return console.log(x); }); </code></pre> <p>Since wrapping console.log in an anonymous function is long and annoying to type I usually add the following global function when I'm developing and debugging:</p> <pre><code>function log(message){ return function(x){ return console.log(message, x); };}; forEach(['asd', 'zxc'], log('-&gt;')); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload