箭頭函數(shù)的作用域是和定義這個(gè)箭頭函數(shù)的父級(jí)上下文綁定在一起的
匿名函數(shù)的作用域是和定義匿名函數(shù)的上下文綁定在一起的
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()
有了箭頭函數(shù)袱贮,再也不用寫that
這種hack