"this" 在箭头函数中的可见性
Visibility of "this" in Arrow Functions
我有两个案例
const test = {
foo: function (){
this.bar();
},
bar: function (){
console.log('bar');
}
}
test.foo();
在这种情况下,一切正常。
const test = {
foo: () => {
this.bar();
},
bar: () => {
console.log('bar');
}
}
test.foo();
在第二种情况下我得到错误:
Uncaught TypeError: Cannot read property 'bar' of undefined
我知道我可以在 foo
函数中写 test.bar()
,但我很感兴趣为什么在这种情况下 this
在箭头函数范围内不可用。
通常,函数中 this
的值取决于该函数的调用方式。
箭头函数从创建函数的范围中导入 this
的值。
在对象字面量中间,this
的值取决于对象字面量周围的内容,但肯定不会是对象本身。
我有两个案例
const test = {
foo: function (){
this.bar();
},
bar: function (){
console.log('bar');
}
}
test.foo();
在这种情况下,一切正常。
const test = {
foo: () => {
this.bar();
},
bar: () => {
console.log('bar');
}
}
test.foo();
在第二种情况下我得到错误:
Uncaught TypeError: Cannot read property 'bar' of undefined
我知道我可以在 foo
函数中写 test.bar()
,但我很感兴趣为什么在这种情况下 this
在箭头函数范围内不可用。
通常,函数中 this
的值取决于该函数的调用方式。
箭头函数从创建函数的范围中导入 this
的值。
在对象字面量中间,this
的值取决于对象字面量周围的内容,但肯定不会是对象本身。