1

I have a code snippet of small javascript program

var obj = {
    id: "awesome",
    cool: function coolFn() {
        console.log( this.id );
    }
};

var id = "not awesome";
obj.cool(); // awesome
setTimeout( obj.cool, 100 ); // not awesome

I didn't understand the result of setTimeout where this.id refers to global id. Why is this happening? Why this binding is lost inside setTimeout?

  • you don't even need to do a `setTimeout`. just say `var id = "not awesome"; var foo = obj.cool; foo(); `. it will output `not awesome` . As soon as you said `obj.cool` it became `coolFn` function (if not named then some anonymous function) and when i did `foo()` it meant `window.foo()`, so the `this` became `window`. – blogbydev Mar 20 '17 at 11:06
  • + if you do `setTimeout ( function(){ obj.cool() } , 100)`, only THEN a correct closure of `obj` goes in the waiting queue. – blogbydev Mar 20 '17 at 11:10

0 Answers0