简体   繁体   中英

this binding in an arrow callback function

I will appreciate your help and explanation. I am unclear on the reason why the second and third alerts in the code below are different from the first one.

Arrow functions have lexical binding. This bit is clear. By why is it that including an arrow function expression as a parameter in an object method call makes a difference for the "this", which somehow gets bound to the global name variable.

var name = "globalscope name";

let person = {
    name: 'Tommy',
   
    showName(a){
        let fun1 = ()=>this.name;
        let fun2 = a;
        alert(fun1()); //Tommy - this is behaving as expected base on lexical binding
        alert(a()); // globalscope name - this is not
        alert(fun2()); //globalscope name
    }
}

person.showName(()=>this.name);

Lexical binding of this means that the this value is copied from where the function is declared.

The function declared on the last line is in a scope where this is window .

The function declared on the first line of showName is in a scope where this depends on how showName is called.


The this value is copied from the scope where the function is declared, not from it was immediately before being passed to the function where it is called.

In this code block person.showName(()=>this.name); this.name is referring to the window object where in the window object name value is globalscope name

And you calling the object method person.showName for which you're just passing a function reference along with this.name (window.name) due to which a() and fun2() providing result globalscope name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM