【问题标题】:Why does arrow function as a JavaScript object property does not get reference of this? [duplicate]为什么箭头函数作为 JavaScript 对象属性没有得到 this 的引用? [复制]
【发布时间】: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 作为对象的引用?

【问题讨论】:

标签: javascript


【解决方案1】:

说白了:就是这样。 Arrow functions 没有绑定到 this

它们与“常规”函数有更多限制和差异。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-01
    • 2017-06-03
    • 2020-03-08
    • 2021-08-20
    • 2016-03-16
    相关资源
    最近更新 更多