O'Reilly logo

You Don't Know JS: Scope & Closures by Kyle Simpson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Appendix C. Lexical this

Though this title does not address the this mechanism in any detail, there’s one ES6 topic that relates this to lexical scope in an important way, which we will quickly examine.

ES6 adds a special syntactic form of function declaration called the arrow function. It looks like this:

var foo = a => {
    console.log( a );
};

foo( 2 ); // 2

The so-called “fat arrow” is often mentioned as a shorthand for the tediously verbose (sarcasm) function keyword.

But there’s something much more important going on with arrow functions that has nothing to do with saving keystrokes in your declaration. Briefly, this code suffers a problem:

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

var id = "not awesome"

obj.cool(); // awesome

setTimeout( obj.cool, 100 ); // not awesome

The problem is the loss of this binding on the cool() function. There are various ways to address that problem, but one often-repeated solution is var self = this;.

That might look like:

var obj = {
    count: 0,
    cool: function coolFn() {
        var self = this;

        if (self.count < 1) {
            setTimeout( function timer(){
                self.count++;
                console.log( "awesome?" );
            }, 100 );
        }
    }
};

obj.cool(); // awesome?

Without getting too much into the weeds here, the var self = this “solution” just ends-around the whole problem of understanding and properly using this binding, and instead falls back to something we’re perhaps more comfortable with: lexical scope. self becomes just an identifier that can be resolved ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required