Why, precisely, does the call to setTimeout alert "Window says hi" rather than "Tom says hi"?
var name = "Window";
var tom = {
name: "Tom",
sayHi: function() {
alert(this.name + " says hi");
}
};
setTimeout(tom.sayHi, 1000);
I understand that the first argument in the invocation of setTimeout, tom.sayHi, is simply the sayHi method on the tom object, found through property lookup on that object, and called after one second by setTimeout:
sayHi: function() {
alert(this.name + " says hi");
}
I also understand that if we wrap the first argument to setTimeout (tom.saysHi) inside an anonymous function and then add the parentheses to invoke it,
setTimeout(function(){ tom.sayHi() }, 1000);
'this' will stay bound to the tom object and correctly alert "Tom says hi."
Why does function(){ tom.sayHi() } have a 'this' value bound to the tom object but tom.sayHi does not? Is it simply because the prior is a function found through property lookup and the latter is a method that is being invoked immediately?