0

Wonder why i cant call class methods in timers without wrapping in functions ?

function Class(){};

Class.prototype.method = function(){

    console.log(this); // -> writes Window then Class 
}

var instance = new Class();


setTimeout(instance.method,10);

setTimeout(function(){
    instance.method();
},20);
triver
  • 19
  • 1
  • 5
  • `setTimeout(instance.method.bind(instance), 10)`, more info on how `this` works here http://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work – elclanrs Jun 12 '16 at 11:32
  • Could you explain why the scope is changed, please. – triver Jun 12 '16 at 11:34
  • `this` depends on the caller. `setTimeout` is the caller. You can think of it like `setTimeout(f, ms)` so it will call the function like `f()`. Notice there is no dot in that call; no dot no `this`, unless it is bound. See the question I linked above for more details. – elclanrs Jun 12 '16 at 11:36

0 Answers0