請問您能告訴我什麼是snippet 1的錯誤?我對obj.discover()的期望輸出是3.我怎樣才能將this
綁定到對象的箭頭函數方法?對箭頭功能感到困惑
'use strict'
// Snippet 1
var obj = {
data: 3,
discover:() => {
return this.data
}
}
obj.discover() // -> undefined
obj.discover.bind(obj)() // undefined
// but if I don't use the arrow notation, everything works
// Snippet 2
var obj2 = {
data: 3,
discover: function(){
return this.data
}
}
obj2.discover() // -> 3
箭頭函數沒有自己的'this',使用該函數的常規函數 –