Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Try this:</p> <pre><code>function TestEngine() { this.id='Foo'; } TestEngine.prototype.fooBar = function() { this.id='bar'; return true; } TestEngine.prototype.start = function() { this.fooBar(); } TestEngine.prototype.startMethod = function() { var self = this; var inter = setInterval(function() { self.start(); }, 200); } var test = new TestEngine(); test.startMethod(); </code></pre> <p><code>setInterval</code> calls <code>start</code> function with window context. It means when <code>start</code> gets executed, <code>this</code> inside <code>start</code> function points to <code>window</code> object. And window object don't have any method called <code>fooBar</code> &amp; you get the error. </p> <h2>Anonymous function approach:</h2> <p>It is a good practice to pass <a href="https://www.google.com/url?sa=t&amp;rct=j&amp;q=&amp;esrc=s&amp;source=web&amp;cd=1&amp;ved=0CC4QFjAA&amp;url=http://helephant.com/2008/08/23/javascript-anonymous-functions/&amp;ei=TlJIUd_wI46KrgeDiYCQCg&amp;usg=AFQjCNEoMND3ig9KdKF1tQrR7gsp6sSAjQ&amp;bvm=bv.43828540,d.bmk&amp;cad=rja" rel="nofollow"><code>anonymous function</code></a> to <code>setInterval</code> and call your function from it. This will be useful if your function makes use of <code>this</code>.</p> <p>What I did is, created a temp variable <code>self</code> &amp; assigned <code>this</code> to it when it is pointing your TestEngine instance &amp; calling <code>self.start()</code> function with it. </p> <p>Now inside <code>start</code> function, <code>this</code> will be pointing to your testInstance &amp; everything will work as expected. </p> <h2>Bind approach:</h2> <p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind" rel="nofollow"><code>Bind</code></a> will make your life easier &amp; also increase readability of your code. </p> <pre><code>TestEngine.prototype.startMethod = function() { setInterval(this.start.bind(this), 200); } </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