簡體   English   中英

如何在JavaScript中調用靜態子類方法

[英]How to call a static subclass method in JavaScript

如何從父類的靜態方法調用子類的靜態方法?

class A {

  static foo(){
    // call subclass static method bar()
  }
}

class B extends A {

  static bar(){
    // do something
  }
}

B.foo()

更新

我嘗試這個的原因是A的子類在我的上下文中最適合作為單例,我想在A中使用模板方法模式

因為看起來我無法從靜態上下文中獲取對子類的引用,所以我現在正在導出A的子類的實例,它們也可以正常工作。 謝謝。

更新2

是的,它是一個程度的重復(另一個問題不涉及子類)。 即使從靜態上下文,引用也是this 這樣可行:

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

我對你的需求有點困惑,因為你似乎已經得到了你需要用B.foo()做的事情。 那么,這就是你需要的嗎?

class A {

  static foo(){
    // call subclass static method bar()
    // Because it is "static" you reference it by just calling it via
    // the class w/o instantiating it.
    B.bar() 

  }
}

class B extends A {

  static bar(){
    // do something
    console.log("I am a static method being called")
  }
}

// because "foo" is static you can call it directly off of 
// the class, like you are doing
B.foo()

// or
var D = new B()
D.bar() // won't work ERROR
A.foo() // Works <-- Is this is specifically what you are asking? Or 
        // calling it in the Super class like B.bar(), that is done in static method foo?

這是你要問的嗎? 如果這不能回答你的問題,請告訴我我的誤解,我會盡力回答。 謝謝。

它使模板模式稍微不那么優雅,但你可以通過子類中的super來實現這一點,例如:

class A {
  static foo() {
    this.bar()
  }
}

class B extends A {
  static foo() {
    super.foo()
  }
  static bar() {
    console.log("Hello from B")
  }
}

B.foo()

暫無
暫無

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

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