问题:@action.bound中的this指向
先看代码截图:

问题描述: 直接执行fn5函数,此时actionTest中返回的this指向undefined;将actionTest作为参数传入响应式组件Input,此时执行fn5函数发现this指向actionTest类
思考:与observer装饰器有没有关系???
对比@action, @action.bound, arrow fn, 普通函数
代码如下:
class ActionTest{
fn1() {
console.log('fn1', this);
}
fn2 = () => {
console.log('fn2', this);
}
@action fn3() {
console.log('fn3', this);
}
@action fn4 = () => {
console.log('fn4', this);
}
@action.bound fn5() {
console.log('fn5', this);
}
@action.bound fn6 = () => {
console.log('fn6', this);
}
}
执行后,查看返回值:

本文探讨了JavaScript中类方法的this指向问题,通过示例展示了@action.bound、箭头函数、普通函数及@action的区别。在直接调用fn5时,this指向undefined,而在响应式组件中调用时,this指向了ActionTest类。这揭示了JavaScript中函数作用域和this绑定的特性,特别是与装饰器observer的关系。
1257

被折叠的 条评论
为什么被折叠?



