loading...

Discussion on: The Common Enemy, JavaScript's "This" Keyword Saves The Day

Collapse
jishvi profile image
Jishnu Vasanth

Arrow function does not create its own this context. Instead, it binds this keyword lexically which is a fancy way of saying that it takes the meaning of this from the enclosing context. In ES5 we can either use Function.prototype.bind to grab the this value from another scope to change a function’s execution context or assign the value of this to another variable (var that = this).

 var Person = function(name) {
    this.name = name;
    this.sayNameAfterTwoSeconds = function() {
        setTimeout(() => {
            alert(this.name)
        }, 2000);
    };
};

In this code caller of setTimeout is window object. But inside setTimeout, this refers to its current surrounding scope and no further. Thus the inner function knew to bind to the inner function only, and not to the object’s method or the object itself.

Thread Thread
jochemstoel profile image
Jochem Stoel
Arrow function does not create its own this context. Instead, it binds this keyword lexically which is a fancy way of saying that it takes the meaning of this from the enclosing context.

That is precisely what I said.