Tuesday, 22 November 2016

Javascript: dabble in 'this'

It is probably going to take me a while to fully grasp the 'this' concept in Javascript. Today I just dabble in the topic and present my shallow understandings.

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))();
} 
Hey it works. I wouldn't have come up with this solution if I hadn't read the previous chapters of 'You Dont Know Js'. So once again, kudos to the author.

No comments:

Post a Comment