It still comes from You Dont Know Js Scope and Closure, Appendix C: Lexical 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
It looks like when invoked from setTimeout(), this refers to the window object. Then the author introduced various solutions, including self, bind(), and a new feature of ES6: arrow function. These are all cool stuff. But how to address the original problem -- that is, to get setTimeout() function to print 'awesome' as well?
The simplest solution is replace this with obj
console.log( obj.id );
Then I attempt to use bind().
cool2: function coolFn2() { console.log( this.id ); }.bind(obj)It doesn't work because obj cannot be referenced within itself, well, unless it is referenced within a function. Therefore the 2nd attempt.
cool3: function coolFn3() { (function(){ console.log(this.id); }.bind(obj))(); }
No comments:
Post a Comment