我如何在箭头函数中访问我的“计数”对象?
const myCounter = {
count: 0,
increment: () => {
this.count += 1
//i know that the arrow functions can't work with "this." ... so how we get access count ??
},
currentValue: () => {
return this.count
}
}
答案 0 :(得分:0)
箭头函数表达式的语法比函数表达式短,并且没有自己的
this
,arguments
,super
或new.target
。这些函数表达式最适合非方法函数,因此不能用作构造函数。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
因此,如果您需要使用this
,请使用function
关键字定义方法:
const myCounter = {
count: 0,
increment: function () {
this.count += 1;
},
currentValue: function () {
return this.count;
}
}