【问题标题】:Call parent function in parent class instead of child (same names) javascript在父类中调用父函数而不是子(同名)javascript
【发布时间】:2020-05-13 02:10:40
【问题描述】:

我有两个同名的函数。一个在子类内部,一个在父级内部。

我想如果我在父类中调用方法,就会调用父类的函数。

但它看起来不像这样工作并调用子函数。

所以我的问题是,如果我在子类中有另一个同名的函数,如何在父类中调用父函数。

我想得到“父母”和“孩子”,但我得到了 2 次“孩子”

class Parent {
  constructor() {
    this.init()
  }
  init() {
    console.log('Parent');
  }
}
class Child extends Parent {
  constructor() {
    super();
    this.init()
  }
  init() {
    console.log('Child');
  }
}
new Child();

【问题讨论】:

标签: javascript inheritance


【解决方案1】:

this 引用子实例,并继承其 .init 方法,该方法隐藏从父实例继承的 .init 方法。要明确地引用它,你会写

class Parent {
  constructor() {
    Parent.prototype.init.call(this)
  }
  init() {
    console.log('Parent');
  }
}

但这是一个非常糟糕的主意,无论是to override a method where the overriding one shouldn't be called,还是一般to call overrideable methods in the constructor。在您的情况下,只需在 constructor 中完成所有工作,然后完全放弃 init 方法。

【讨论】:

    猜你喜欢
    • 2011-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多