0

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?

ShaneM
  • 93
  • 1
  • 6
  • Have a look here: http://stackoverflow.com/questions/591269/settimeout-and-this-in-javascript – le_m Jun 14 '16 at 03:31
  • Btw - it should be a duplicate of that question, not the one currently chosen by @Paulpro – le_m Jun 14 '16 at 03:31
  • @le_m I disagree. The answer to that question is basically just to wrap the function in an anonymous function, which the OP of this question already knows how to do. His question is more about the ***why*** it acts the way it does, as in "How does `this` work?" than "Help me get my `setTimeout` to work" – Paul Jun 14 '16 at 03:33
  • 1
    `Is it simply because the prior is a function found through property lookup and the latter is a method that is being invoked immediately` Yes... `this` is bound at call time to the object that the function reference is a property of. If a function is called without an object to assign as `this`, then the global object is used in non-strict mode. In strict mode `this` would be `undefined` instead of `window`. – Paul Jun 14 '16 at 03:35
  • @Paulpro valid point – le_m Jun 14 '16 at 03:36

0 Answers0