ECMAscript新特性 - 箭头函数与 this

171 阅读1分钟

相比于普通函数箭头函数还有一个非常重要的变化,就是不会改变 this 的指向。

const person = {
    name: 'Tom',
    sayHi: function () {
        console.log(`hi, my name is ${this.name}`)
    }
}
person.sayHi() // hi, my name is Tom

如果将 sayHi 方法修改成箭头函数,你会发现 this.name 打印出来的是 undefined 。这就是箭头函数和普通函数最重要的区别,因为在箭头函数当中没有 this 的机制所以说它不会改变 this 的指向。也就是说在箭头函数外面 this 是什么,那么在里面拿到的 this 就是什么任何情况下都不会发生改变。

const person = {
    name: 'Tom',
    sayHi: () => {
        console.log(`hi, my name is ${this.name}`)
    },
    sayHiAsyncThis: function () {
        setTimeout(function(){
            // 异步函数会被放在全局对象上被调用
            console.log(this.name)
        }, 1000)
    },
    sayHiAsync_this: function () {
        // 通常解决此类问题,都会借助闭包的方式
        // 在外部定义一个 _this 来存储 this
        const _this = this
        setTimeOut(function(){
            console.log(_this.name)
        },1000)
     }
    sayHiAsyncArrow: function () {
        // 在箭头函数当中 this 始终指向的是当前作用域里面的 this
        setTimeOut(() => {
            console.log(this.name)
        }, 1000)
    }    
}
person.sayHi() // hi, my name is undefined
person.sayHiAsyncThis() // undefined
person.sayHiAsync_this() // Tom
person.sayHiAsyncArrow() // Tom