this指向摸不着头脑?快来学这篇

54 阅读1分钟

1.function声明的普通函数

1)直接执行,this指向window(严格模式下指向undefined)。

2)被谁调用,this就指向谁。

    function fn(){
        console.log(this)
    }
    fn() // 直接调用,this指向window(严格模式就指向undefined)
    
    const person = {fn, name: 'xxx'}
    person.fn() // 被person调用,this指向person

2.箭头函数

和声明时的上下文this保持一致

function run(){
    (() => {
        console.log(this)
    })()
}
run() //直接调用,内部箭头函数 this指向window(严格模式就指向undefined)

const xiaoming = {run, name:'xiaoming'}
xiaoming.run() // 被xiaoming调用,内部箭头函数的this指向xiaoming

3.function声明的函数被api改变指向

1)call,apply,bind这些方法可以改变普通函数的this指向

2)箭头函数的this不会被call,apply,bind影响

function eat() {
    console.log(this)
}
const cat = {name: 'cat'}
const dog = {name: 'dog'}
const pig = {name: 'pig'}

eat.call(cat) // this指向cat
eat.apply(dog) // this指向dog
eat.bind(pig)() // this指向pig

执行结果

image.png


image.png


image.png

总结

  1. 普通函数看是否被调用
  2. 箭头函数看声明时的上下文
  3. bind,call,apply只会影响普通函数