相关疑难解决方法(0)

ES6 - 在类中调用静态方法

我有这个类对静态方法进行内部调用:

export class GeneralHelper extends BaseHelper{
     static is(env){
          return config.get('env:name') === env;
     }

     static isProd(){
         return GeneralHelper.is('prod');
     }
 }
Run Code Online (Sandbox Code Playgroud)

我可以使用任何关键字来替换下面一行中的类名:

GeneralHelper.is('prod');
Run Code Online (Sandbox Code Playgroud)

在PHP中也有self,static等ES6是否提供类似这些东西吗?

TY.

javascript oop ecmascript-6

70
推荐指数
3
解决办法
4万
查看次数

从类静态方法调用 ES6 类构造函数

我正在尝试在 JS ES6 类中实现单例模式。这是我到目前为止所写的:

let instance;

export class TestClass{

    constructor(){
        if(new.target){
            throw new Error(`Can't create instance of singleton class with new keyword. Use getInstance() static method instead`);
        }
    }
    testMethod(){
        console.log('test');
    }
    static getInstance(){
        if(!instance) {
            instance = TestClass.constructor();
        }

        return instance;
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,当我调用静态方法时TestClass.getInstance(),我没有得到类对象的实例,我得到了

ƒ anonymous() {

}
Run Code Online (Sandbox Code Playgroud)

函数,无需访问 testMethod。我在我的代码中找不到错误 - 将不胜感激。

javascript singleton constructor ecmascript-6 es6-class

5
推荐指数
1
解决办法
5385
查看次数