4

Let's see examples:

first:

var user = {
  firstName: "John",
  sayHi: function() {
  alert( this.firstName );
  }
};

setTimeout(function() {
  user.sayHi(); // John
}, 1000);

second:

var user = {
  firstName: "John",
  sayHi: function() {
  alert( this.firstName );
  }
};

setTimeout(user.sayHi, 1000);// undefined

Why in the second example undefined? And how does that work?

Jim Button
  • 151
  • 1
  • 7

1 Answers1

4

When you pass a function reference to a setTimeout function, the passed function reference will be executed in the window's scope. So window.firstName will be undefined as you don't have any property in window object like that.

var user = {
  firstName: "John",
  sayHi: function() {
  alert( this.firstName );
  }
};

setTimeout(user.sayHi.bind(user), 1000);

So as you can see in the above code, you have to explicitly bind the scope to the function reference. And also you can use the traditional way, that is using an anonymous function like below,

setTimeout(function(){ user.sayHi(); }, 1000);
Rajaprabhu Aravindasamy
  • 63,064
  • 13
  • 90
  • 119
  • Thank you but i don't understand how works your example with anonymous function? How that saves context? – Jim Button Mar 19 '16 at 16:06
  • @JimButton With the anonymous function, It becomes a closure. I mean the object user. But with the first case, Internally setTimeout will call the passed function reference like `reference.call(scope)` where scope will be the window if it was not overridden. so this.firstName would be similar to window.firstName. – Rajaprabhu Aravindasamy Mar 19 '16 at 16:11
  • 1
    Thank you for your help! – Jim Button Mar 19 '16 at 16:14