re: The Common Enemy, JavaScript's "This" Keyword Saves The Day VIEW POST

VIEW FULL DISCUSSION

I think, by using lexical scoping, arrow function solves the confusion around this to an extent.

Yurp, ure right. Thanks alot for the additional information

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.

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.

code of conduct - report abuse