Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The <code>this</code> pointer can point to one of many things depending upon the context:</p> <ol> <li>In constructor functions (function calls preceded by <code>new</code>) <code>this</code> points to the newly created instance of the constructor.</li> <li>When a function is called as a method of an object (e.g. <code>obj.funct()</code>) then the <code>this</code> pointer inside the function points to the object.</li> <li>You can explicitly set what <code>this</code> points to by using <code>call</code>, <code>apply</code> or <code>bind</code>.</li> <li>If none of the above then the <code>this</code> pointer points to the global object by default. In browsers this is the <code>window</code> object.</li> </ol> <p>In your case you're calling <code>this.start</code> inside <code>setInterval</code>. Now consider this dummy implementation of <code>setInterval</code>:</p> <pre><code>function setInterval(funct, delay) { // native code } </code></pre> <p>It's important to understand that <code>start</code> is not being called as <code>this.start</code>. It's being called as <code>funct</code>. It's like doing something like this:</p> <pre><code>var funct = this.start; funct(); </code></pre> <p>Now both these functions would normally execute the same, but there's one tiny problem - the <code>this</code> pointer points to the global object in the second case while it points to the current <code>this</code> in the first.</p> <p>An important distinction to make is that we're talking about the <code>this</code> pointer inside <code>start</code>. Consider:</p> <pre><code>this.start(); // this inside start points to this var funct = this.start; funct(); // this inside funct (start) point to window </code></pre> <p>This is not a bug. This is the way JavaScript works. When you call a function as a method of an object (see my second point above) the <code>this</code> pointer inside the function points to that object.</p> <p>In the second case since <code>funct</code> is not being called as a method of an object the fourth rule is applied by default. Hence <code>this</code> points to <code>window</code>.</p> <p>You can solve this problem by binding <code>start</code> to the current <code>this</code> pointer and then passing it to <code>setInterval</code> as follows:</p> <pre><code>setInterval(this.start.bind(this), 200); </code></pre> <p>That's it. Hope this explanation helped you understand a little bit more about the awesomeness of JavaScript.</p>
 

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