gpt4 book ai didi

javascript - 'this' 在子类中未定义

转载 作者:行者123 更新时间:2023-11-30 10:59:48 26 4
gpt4 key购买 nike

我不能在快速 route 使用“this”。这是为什么?因为我在B类的多个方法中需要this.postRepo。有什么替代方法吗?

// Parent
export default abstract class A {
// no constructor
// few methods
}

// Child
export default class B extends A {
public postRepo: number

constructor() {
super();
this.postRepo = 111;
}

public methodA(req?: Request, res?: Response): any {
console.log(this); // undefined
console.log(this.postRepo); // TypeError: Cannot read property 'postRepo' of undefined
}

// ...methods that required this.postRepo
}

// New
const classB = new B();
classB.methodA(); // <--- this is working
router.get("/", classB.methodA); // <--- undefined

最佳答案

我以为方法正在失去它的上下文。如果是这样,你可以用箭头函数替换方法,它们的上下文是稳定的:

public methodA = (req?: Request, res?: Response) => {
console.log(this); // undefined
console.log(this.postRepo); // TypeError: Cannot read property 'postRepo' of undefined
}

关于javascript - 'this' 在子类中未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58315898/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com