提问人:Shannon Hochkins 提问时间:1/4/2023 最后编辑:Shannon Hochkins 更新时间:1/4/2023 访问量:267
将带有“this”的正确上下文从类传递到外部方法
Passing correct context with "this" to external method from class
问:
假设我有一个非常简单的类,它扩展了其他类,以及一个要传递给类 B 的函数对象
const actions = {
doSomething: (this: B, foo: boolean) => {
console.log('from do something', this.text, foo);
}
}
class B {
actions = actions;
text: string;
constructor() {
this.text = 'abc';
}
}
class A extends B {
runAction(foo) {
this.actions.doSomething(false);
}
}
const instance = new A();
instance.runAction(); // 'from do something, undefined, false'
TS 编译器还说从内部调用时上下文不正确this
runAction
有没有更好的方法可以做到这一点?
我们有 500 多个操作,我们希望为每个操作提供对类数据的访问,并且不希望通过所有操作传递参数。
答:
1赞
CertainPerformance
1/4/2023
#1
这
this.actions.doSomething(false);
使用 的 调用方法。但是是带有方法的普通对象 - 而不是实例本身。您将需要改用,以及将箭头函数更改为常规函数/方法,以便它可以捕获不同的 .参数也应该被键入(或删除)。this
this.actions
this.actions
doSomething
.call
doSomething
this
foo
在里面打字也很有用,尽管并不总是必要的。this
runAction
const actions = {
doSomething(this: B, foo: boolean) {
console.log('from do something', this.text, foo);
}
}
class A extends B {
runAction(this: A) {
this.actions.doSomething.call(this, false);
}
}
评论
0赞
Shannon Hochkins
1/4/2023
谢谢,这么简单,我应该知道这一点......
评论
actions.doSomething(this, false)
actions = actions
actions
B