解读typescript中 super关键字的用法

解读typescript中 super关键字的用法

传统的js,使用prototype实现父、子类继承.

如果父、子类有同名的方法,子类去调用父类的同名方法需要用 “父类.prototype.method.call(this)”.

但是在typescript中,提供了一个关键字super,指向父类.

super.method() 这样就可以达到调用父类同名的方法.

class Animal {
      constructor() {
             console.log('animal')
      }
      get() {
             console.log("吃饭")
      }     
}  

class Monkey extends Animal {
      constructor() {
              console.log("child---monkey")
              super()
      }
      get() {
             console.log("不吃饭")
      }
      init() {
              super.get()
      }
}  

var animal = new Monkey();
animal.init();