ECMAScript -9: 箭头函数中的this
// 🚩🚩 箭头函数不会改变this的指向
const person = {
name: 'tom',
// 🚀 在普通函数中, this会指向调用这个函数的对象
sayHiNormal: function () {
console.info(`${this.name} in normal function.`) // >>> tom in normal function.
},
// 在箭头函数中,没有this的机制,它不会改变this的指向
// 在箭头函数外部的this是什么,箭头函数内部的this就是什么
// 它里面的this是继承于上一级的上下文
sayHiArrow: () => {
console.info('this', this) // {}
console.info(`${this.name} in arrow function.`) // >>> undefined in arrow function.
},
sayHiAsyncNormal: function () {
/**
* setTimeout 的完整写法其实是window.setTimeout
* 在js中window是可以省略不写的,对于这种普通的回调函数,它里面的this指向的是window
*/
setTimeout(function () { // setTimeout内的普通函数会放在全局作用域下被调用-全局对象
console.info(`${this.name} in normal function.`) // >>> undefined in normal function.
}, 1000);
},
sayHiAsyncArrow: function () {
/**
* 如果是箭头函数,那么这个setTimeout中的回调函数内是没有this指向的,
* 这个this是来自于上一级sayHiAsyncArrow的上下文person环境
*/
setTimeout(() => { // 箭头函数中的this始终指向当前作用域的this,也就是person对象
console.info('this', this) // person对象
console.info(`${this.name} in arrow function.`) /// >>> tom in arrow function.
}, 1000);
},
}
person.sayHiNormal() // tom in normal function.
person.sayHiArrow() // this {} | undefined in arrow function.
person.sayHiAsyncNormal() // undefined in normal function.
/**
this {
name: 'tom',
sayHiNormal: [Function: sayHiNormal],
sayHiArrow: [Function: sayHiArrow],
sayHiAsyncNormal: [Function: sayHiAsyncNormal],
sayHiAsyncArrow: [Function: sayHiAsyncArrow]
}
tom in arrow function.
*/
person.sayHiAsyncArrow()
/**
* this { name: 'this name' }
* this name in arrow function.
*/
this.name = 'this name'
person.sayHiArrow.apply(this, [])
Keep learning

浙公网安备 33010602011771号