当前位置:网站首页>This point of arrow function

This point of arrow function

2022-06-11 06:06:00 No baldness

Statement :call、apply、bind Can't change the arrow function this Point to
for example :

const fun1 = ()=>{
    
    console.log(this === window)
}
const person = {
    
    name:'tom'
}
fun1()  // true
fun1.apply(person)  // true
fun1.bind(person)  // true
fun1.call(person)  // true

You can see that the arrow function initially points to window, Use apply、bind、call To try to change its direction , They all failed , Always point to window
Conclusion The arrow function points to the object that is its grandfather . That is, the parent object of the parent .
prove :

const obj = {
    
    name:'obj',
    fun1:function (){
    
        return setTimeout(()=>{
    
            console.log(this.name)
        },1000)
    }
}
const person = {
    
    name:'person',
    age:'22'
}
obj.fun1() // obj
obj.fun1.apply(person)  //person

You can see , We are setTimeout The arrow function is called ,setTimeout Is a global function , It points to window, Then we were obj Object setTimeout, Arrowhead function this Parent pointing to parent , Here, it points to obj
 Insert picture description here

It was said that , We cannot change the direction of the arrow function , But we can change the direction of its parent , Because the arrow function points to the parent of the parent , It means that we have changed the direction of the arrow function . In the example, we changed fun1 The direction of , Successfully changed the direction of the arrow function .

原网站

版权声明
本文为[No baldness]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/162/202206110553223777.html