2016-08-18 20 views
0

如何从父类的静态方法调用子类的静态方法?如何在JavaScript中调用静态子类方法

class A { 

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

class B extends A { 

    static bar(){ 
    // do something 
    } 
} 

B.foo() 

更新

为什么我想这是一个子类会工作最好的,因为在我的情况下单身,我想在A.使用template method pattern原因

由于它看起来像我无法从静态上下文中获取对子类的引用现在我正在导出A的子类实例,它的工作原理也是如此。谢谢。

更新2

是的,这是一个重复的程度(其它问题不涉及子类)。该参考,即使从静态的上下文,是this。所以这个工程:

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

我相信你有javascript有点困惑,https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes – Derek

+0

可以@你指向一个特定的部分,请? https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes#Static_methods – hcvst

+0

你想达到什么目的?你没有在子类中的基类中声明任何东西。所以调用'B.foo()'不会返回任何东西。 – Dandy

回答

0

我有点困惑你的需要,因为它似乎你已经得到你需要做的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? 

这是你在问什么?如果这不能回答你的问题,请让我知道我的误解,我会尽力回答。谢谢。

+0

谢谢@james。因为'A'可以有不同的子类,所以不用明确地调用'B.bar()'我会喜欢调用类似'subClassRef.bar()'的东西。 – hcvst

相关问题