ES6 has been used for a long time, so it feels a little late to write this article. However, I was struggling with this problem when I was working on the project yesterday. I read several top-ranking articles online, but I didn’t fully understand them, or I always felt that the statements in the articles were not completely correct. The arrow function does not create its own this, but inherits this from the upper level of its scope chain

Without further ado, let’s look at some examples:

const obj = { a: () => {console.log(this)}} obj.a() => {console.log(this)}} obj.a()Copy the code
function foo() {
    return(a) => {
        console.log(this.a);
    }
}
var obj1 = {
    a:2
};
var obj2 ={
    a:3
};
foo()() // undefined
foo.call(obj1)() // 2
foo.call(obj2)() // 3  
Copy the code

Unlike traditional functions, arrow functions cannot be changed by apply, bind, call, etc. From the definition, their this reference is fixed, that is, static scope. It is important to note, however, that pointing to static does not mean that the value is static. Since it always points to this in the upper scope, the value of this can be changed by apply,bind,call as long as the upper scope is a function scope (before block scopes, JS had only function scopes and global scopes). So the results in the above example are undefined, 2, and 3 respectively