在继承的类中执行构造函数之前调用的方法

时间:2019-03-02 19:42:39

标签: javascript node.js oop inheritance

考虑以下Javascript代码:

class Component {

  constructor() {
    /* ... */
    this.retrieveContentFromServer()
  }

  retrieveContentFromServer() {
    /* ... */
  }

}

class TextInput extends Component {

  constructor() {
    super()
    this.jqElmt = $('<input type="text" />')
    /* ... */
  }

  retrieveContentFromServer() {
    super.retrieveContentFromServer()

    console.log(this.jqElmt) // undefined
    // this.jqElmt.val(/* ... */)
  }

}

new TextInput()

console.log(this.jqElmt)创建新对象时,undefined返回TextInput,这是预期的。我的目标是使其返回构造函数中创建的jQuery对象,以便我们可以编辑从服务器检索到的文本输入内容。

那么我该如何更改这段代码,以便:

  • TextInputComponent的构造函数在调用任何TextInput方法之前都已完全执行
  • 我们能够从Component构造函数中调用方法

我不知道是否有可能...

0 个答案:

没有答案