调用在父类中重写的函数

时间:2016-01-03 07:49:18

标签: javascript class prototype ecmascript-6

有两个班级:

class Parent {
   foo () {
      console.log("foo parent");
   }
}

class Child extend Parent {
   foo () {
      console.log("foo child");
      // Is there a better way than this?
      Parent.prototype.foo.call(this);
   }
}

而不是Parent.prototype.foo.call(this) - 有更好的方法吗?

要调用父构造函数,我使用super。我在想是否有类似的方法来调用在子类中重写的原始函数(来自父级)。

1 个答案:

答案 0 :(得分:4)

super也可以与常规方法一起使用:

class A {
  foo() {
    console.log("hello world");
  }
}

class B extends A {
  foo() {
    super.foo();
  }
}

// outputs "hello world" to the console log
new B().foo();
相关问题