0

Basically i start with this when document is ready:

var newObj = new MyClass(variables);
newObj.start();

And MyClass looks like this (simplying it here)

var MyClass = function(){

    this.start = function(){
         this.loop();
    }

    this.loop = function(){
        // do lots of stuff here
        setTimeout(function(){this.loop();}, 1000);
    }

} // end MyClass

During runtime it tells me that 'this.loop' is not a function at the line where setTimeout is called

What am i missing?

Thanks

Liam
  • 27,717
  • 28
  • 128
  • 190
Matt
  • 278
  • 3
  • 12
  • Could you try [binding](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind) the callback function to `this`? – pushkin Jan 26 '18 at 16:30
  • 2
    Tl;Dr `this` in that setTimeout does not point to what you think it does. [The issue is that setTimeout() causes javascript to use the global scope. Essentially, you're calling the method() class, but not from "this". Instead you're just telling setTimeout to use the function "method", with no particular scope.](https://stackoverflow.com/a/591343/542251) – Liam Jan 26 '18 at 16:31
  • Your problem is slightly different. Even without `setTimeout`, `(function(){this.loop();})();` wouldn't work. Every function call sets `this`. – melpomene Jan 26 '18 at 16:33

0 Answers0