【问题标题】:Typescript imitation problems [duplicate]打字稿模仿问题[重复]
【发布时间】:2018-09-13 11:39:42
【问题描述】:

您好,我在打字稿中有以下错误:

class A {
    constructor() {
        this.init();
    }

    public init() {
        console.log('a')
    }
}

class B extends A {
    constructor(public text) {
        super();
    }
    public init() {
        console.log(this.text)
    }
}

new B('text');

控制台写入未定义。 可以做些什么来克服它。

【问题讨论】:

    标签: typescript oop


    【解决方案1】:

    发生这种情况是因为super() 调用是当您调用new B('text') 时首先调用的,超级调用立即调用this.init(),因为thisB 的实例,而不是A,它尝试调用console.log(this.text) 而不是console.log('text')。但是this.text 只设置在超级调用之后,而不是之前。

    这就是为什么你不应该在构造函数中工作。 在构造函数完全完成运行之前,您的对象还没有准备好执行操作

    您应该从父的构造函数中删除init() 调用,并单独调用它,如下所示:

    class A {
        public init() {
            console.log('a')
        }
    }
    
    class B extends A {
        constructor(public text: string) {
            super(); // no longer strictly needed, as parent has no constructor anymore.
        }
        public init() {
            console.log(this.text)
        }
    }
    
    const b = new B('text');
    // only now the object is ready.
    b.init();
    

    【讨论】:

      【解决方案2】:
      class B extends A {
          public text:string;
          constructor(public text) {
              super();
              this.text = text;
          }
          public init() {
              console.log(this.text)
          }
      }
      

      这样试试

      【讨论】:

      • 不起作用。重复标识符“文本”。
      猜你喜欢
      • 2019-11-13
      • 2020-09-25
      • 1970-01-01
      • 1970-01-01
      • 2019-07-09
      • 2015-12-17
      • 2019-02-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多