箭头函数的作用域是和定义这个箭头函数的父级上下文绑定在一起的
匿名函数的作用域是和定义匿名函数的上下文绑定在一起的
luke = {
id: 2,
say: function() {
setTimeout(function() {
console.log(this.id)
}, 50)
},
sayWithThat: function() {
let that = this
setTimeout(function() {
console.log(that.id)
}, 50)
},
sayWithArrow: function() {
setTimeout(() => {
console.log(this.id)
}, 50)
},
sayWithGlobalArrow: () => {
setTimeout(() => {
console.log(this.id)
}, 50);
}
}
luke.say()
luke.sayWithThat()
luke.sayWithArrow()
luke.sayWithGlobalArrow()
有了箭头函数,再也不用写that
这种hack
网友评论