从子 class 更改 parent 的 class 静态方法

Changing parent's class static method from a subclass

我需要从子class更改Parent的静态方法。

来自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 class 和一个调用 bar() 方法(均为静态)的 foo() 方法。我需要将 barChild subclass 更改为调用 Child.foo() 将调用修改后的 bar 方法而不是原始方法。

是否有可能(可能是 Child 的 constructor 中的某些内容)?

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!)

如果你想修改子项的父项,就这样做吧。 parent是一个有属性的对象,static是语法糖。替换一个方法很简单,设置一个属性。可能不是您想在生产代码中做的事情。

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

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

class Child extends Parent {
  static unhack() {
      if (Parent.hack) {
          Parent.bar = Parent.hack
          delete Parent.hack
      }
  }
  
  static hack() {
    if (!Parent.hack) {
       Parent.hack = Parent.bar
       Parent.bar = Child.bar
    }
  }
 
  static foo() {
      Child.hack()
      Parent.foo()
      Child.unhack()
  }

  static bar() {
    if (super.hack) {
      super.hack(); // Call the "shadowed" Parent.bar()
    }
    console.log(", FELLAS!"); // Call the additional code
  }
}

Parent.foo(); // HERE I AM
Child.foo(); // HERE I AM, FELLAS! (need this!)
Parent.bar(); // HERE I AM
Child.bar(); // Probably don't want to do 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 class,并调用其覆盖的 bar方法。

唯一的选择(如果您不能修改 Parent)将是也覆盖 foo 方法,复制 Parent 代码但在那里显式调用 Child.bar() .