Im reading through the YDKJS books and I thought I understood lexical this
for the most part.
However there is a section with code that shows this:
var obj = {
id: "awesome",
cool: function coolFn() {
console.log( this.id );
}
};
var id = "not awesome";
obj.cool(); // awesome
setTimeout( obj.cool, 100 ); // not awesome
Ok so the first obj.cool()
makes sense of course....but why is the setTimeout
printing not awesome
.....I mean it's still calling obj.cool()
which this
refers to it's own objects id
?
Or does setTimeout get called as another function that calls obj.cool()
? but even in that case (Which I tried calling obj.cool()
inside another function that also had an id
property and it still printed the right one......so why would the this
change with setTimeout?