首页 > 解决方案 > 在Javascript中调用类的其他静态方法中的静态方法

问题描述

我有一个带有一些静态方法的类。我试图在同一类的另一个静态方法中调用我的一个静态方法。

我试图用它来调用它,this.constructor.method();但它不起作用,因为它在那里没有正确绑定。

如果我想调用其他方法,我也尝试将 this 绑定到该方法。this.constructor.listenerFunc.bind(this.constructor). 还是行不通。

代码如下所示:

class MyClass {
    constructor() {
    };

    static firstMethod(){
        //do some things
        this.constructor.secondMethod();
    };

    static secondMethod(){
        //do other things
    };
}

var x = new MyClass;

console.log(x)

标签: javascript

解决方案


除了阻止您的示例工作的错字之外,您还可以使用this.符号和经典的静态调用

class MyClass {
    constructor() {
    };

    static firstMethod(){
        this.secondMethod();
        MyClass.secondMethod();
    };

    static secondMethod(){
        console.log('I was called!');
    };
}

MyClass.firstMethod();


推荐阅读