【发布时间】:2021-06-19 01:25:04
【问题描述】:
var obj = {count: 0}
obj.increment = () => { this.count = this.count +1}
obj.increment()
console.log(obj.count)// outputs "error: Uncaught TypeError: Cannot read property 'count' of undefined"
但是
var obj = {count: 0}
obj.increment = function() { this.count = this.count +1}
obj.increment()
console.log(obj.count) //outputs correct count
为什么箭头函数没有得到 this 作为对象的引用?
【问题讨论】:
-
相关:How does the “this” keyword work?的箭头函数小节。
标签: javascript