簡體   English   中英

從子類更改父類的靜態方法

[英]Changing parent's class static method from a subclass

我需要從子類更改Parent的靜態方法。

來自https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static我讀到:

靜態方法調用直接在類上進行,並且在類的實例上不可調用。

在下面的例子中,我有一個帶有foo()方法的Parent類,它調用bar()方法(都是靜態的)。 我需要從Child子類更改bar ,以便調用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!)

你的問題是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()

如果你想從孩子那里修改父,那就去做吧。 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 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM