【问题标题】:'this' undefined in child class'this' 在子类中未定义
【发布时间】:2019-10-10 05:20:49
【问题描述】:

我不能在快速路线中使用“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

【问题讨论】:

    标签: javascript node.js typescript express


    【解决方案1】:

    我想 methodA 正在失去它的上下文。如果是这种情况,您可以将方法替换为箭头函数,它们的上下文是稳定的:

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

    【讨论】:

      【解决方案2】:

      在构造函数中绑定methodA。

      this.methodA = this.methodA.bind(this);

      // Child
      export default class B extends A {
        public postRepo: number
      
        constructor() {
          super();
          this.postRepo = 111;
          this.methodA = this.methodA.bind(this); // add this line
        }
      
        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
      }
      

      【讨论】:

        【解决方案3】:

        感谢一位在我的 Facebook 帖子上回复的人

        classB.methodA.bind(classB) 是解决方案

        【讨论】:

          【解决方案4】:

          router.get("/", classB.methodA);在这里,您正在引用该方法,这意味着它不会携带您定义该方法的实例的上下文。要么使用 .bind 方法,要么使用箭头函数绑定上下文。

          【讨论】:

            【解决方案5】:

            因为调用者不是classB。 这将是未定义的默认绑定

            【讨论】:

              猜你喜欢
              • 2011-04-30
              • 2018-08-01
              • 2016-04-03
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2019-03-29
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多