javascript - 从子类更改父类的静态方法

标签 javascript inheritance ecmascript-6 es6-class

我需要从子类更改父类的静态方法。

来自 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static我阅读:

Static method calls are made directly on the class and are not callable on instances of the class.

在下面的例子中,我有一个 Parent 类,它有一个 foo() 方法调用 bar() 方法(都是静态的).我需要从 Child 子类更改 bar 以便调用 Child.foo() 将调用修改后的 bar 方法而不是原始方法。

是否有可能(可能是在 Child 的构造函数中)?

class Parent {

  static foo() {
    Parent.bar();
  }

  static bar() {
    console.log("HERE I AM");
  }

}

class Child extends Parent {

  static bar() {
    super.bar(); // maybe not what I want?
    console.log(", FELLAS!");
  }
}

Parent.foo(); // HERE I AM
Child.foo(); // HERE I AM, FELLAS! (need this!)

最佳答案

您的问题是 foo 直接调用 Parent.bar(),而不是 this.bar()。通过显式引用 Parent,它根本不考虑 Child 中的覆盖方法。 Child.bar怎么写,是否调用super.bar都没有关系。

class Parent {
  static foo() {
    this.bar();
//  ^^^^
  }
  static bar() {
    return "HERE I AM";
  }
}

class Child extends Parent {
  static bar() {
    return super.bar() + ", FELLAS!";
  }
}

console.log(Parent.foo()); // HERE I AM
console.log(Child.foo()); // HERE I AM, FELLAS!

static bar() 方法中的 this 关键字现在引用 Child.foo() 中的 Child 调用,并调用其重写的 bar 方法。

唯一的选择(如果你不能修改Parent)是重写foo方法,复制Parent代码但是调用Child.bar() 明确存在。

关于javascript - 从子类更改父类的静态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57245090/

相关文章:

javascript - Material-UI 自动完成仅存储对象的单个属性

javascript - 组中 overflow hidden 的元素

javascript - Jquery 根据部分匹配从数组中删除条目

Python 动态继承 : How to choose base class upon instance creation?

java - 理解这个 Java 程序的执行流程

javascript - 为 react 组件传递 Prop 的最佳方式

javascript - 如何暂时禁用滚动?

c++ - VTBL在单继承和多继承中的区别

javascript - 通过使用 Map Filter 与对象数组进行比较来返回字段

typescript - 如何修改JSDoc block 注释代码