箭头函数没有this的机制,箭头函数不会改变this的指向
第一个例子
const person = {
name:'tom',
sayHi:function(){
console.log(`hi,my name is ${this.name}`)
}
}
person.sayHi()// hi,my name is tom
const person = {
name:'tom',
sayHi:()=>{
console.log(`hi,my name is ${this.name}`)
}
}
person.sayHi()// hi,my name is undefined
第二个例子
const person = {
name:'tom',
sayHiAsync:function(){
setTimeout(function(){
// 这个回调函数最终会被放在全局对象上调用,所以拿不到this.name。输出undefined
console.log(this.name)
},1000)
}
}
person.sayHiAsync()// undefined
那如果想在setTimeout回调函数里拿到this.name,怎么做呢?
以前的解决方案:把当前this存下来,借助闭包
const person = {
name:'tom',
sayHiAsync:function(){
// 借助闭包
const _this = this;
setTimeout(function(){
console.log(_this.name)
},1000)
}
}
person.sayHiAsync()// tom
有了箭头函数之后,我们就不用这么麻烦了:
// 现在的做法。箭头函数
const person = {
name:'tom',
sayHiAsync:function(){
// 箭头函数的this始终指向当前作用域的this
setTimeout(()=>{
console.log(this.name)
},1000)
}
}
person.sayHiAsync()// tom
总结一下:
但凡需要使用_this 这种情况,我们都可以使用箭头函数去避免
本文探讨了ES2015中箭头函数的特点,重点在于其不绑定this值的特性,从而解决了在回调函数中处理this指针的问题。通过实例展示了如何在不需要额外保存this的情况下,利用箭头函数简化代码。
1294

被折叠的 条评论
为什么被折叠?



