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 - Cordova 3.0 ios 地理定位如何停止每个屏幕的警报

javascript - 一个一个展示一个产品div

javascript - 获取一系列连接的项目

javascript - 如何使用 es6 从模块中导入所有内容?

javascript - 是否有允许字符串在 JS 中发生变异的解决方法?或者将复杂的 CSS 声明为 NOT 字符串?

javascript - 记录jQuery中调用的方法和参数

Java函数调用性能优化

javascript - ECMAScript 5 定义 - 构造和继承的通用工厂模式,[ Object.create()]

python - 我如何在python中将相同的列表对象分配给两个不同的变量名?

javascript - 在 promise 中,回调顺序是否有保证?