为什么 this.add 不是对象上下文中的函数
Why this.add is not a function in the object context
在下面的例子中我不太明白为什么没有定义this.add
。我怀疑这是因为箭头函数在编译时立即执行,而 add
函数尚不存在。这个假设是否正确?或者我遗漏了什么。
const arr= [1, 2, 3]
const squares = {
num: (arr) => {
return arr.map((x) => {
return (x * x) + this.add()
})
},
add: () => {
return 1
}
}
//TypeError: this.add is not a function
console.log(squares.num(arr))
您一直在使用 lexical this
对象。您需要避免对 num
:
使用箭头函数
参见documentation for arrow functions:
"An arrow function expression has a shorter syntax than a function expression and does not bind its own this..."
const arr = [1, 2, 3]
const squares = {
num: function(arr) {
return arr.map((x) => {
return (x * x) + this.add()
})
},
add: () => {
return 1
}
}
console.log(squares.num(arr))
在下面的例子中我不太明白为什么没有定义this.add
。我怀疑这是因为箭头函数在编译时立即执行,而 add
函数尚不存在。这个假设是否正确?或者我遗漏了什么。
const arr= [1, 2, 3]
const squares = {
num: (arr) => {
return arr.map((x) => {
return (x * x) + this.add()
})
},
add: () => {
return 1
}
}
//TypeError: this.add is not a function
console.log(squares.num(arr))
您一直在使用 lexical this
对象。您需要避免对 num
:
参见documentation for arrow functions:
"An arrow function expression has a shorter syntax than a function expression and does not bind its own this..."
const arr = [1, 2, 3]
const squares = {
num: function(arr) {
return arr.map((x) => {
return (x * x) + this.add()
})
},
add: () => {
return 1
}
}
console.log(squares.num(arr))