Simplest/Cleanest way to implement singleton in JavaScript?

后端 未结 30 1457
名媛妹妹
名媛妹妹 2020-11-22 05:17

What is the simplest/cleanest way to implement singleton pattern in JavaScript?

30条回答
  •  不知归路
    2020-11-22 05:44

    You can do it with decorators like in this example below for TypeScript:

    class YourClass {
    
        @Singleton static singleton() {}
    
    }
    
    function Singleton(target, name, descriptor) {
        var instance;
        descriptor.value = () => {
            if(!instance) instance = new target;
            return instance;
        };
    }
    

    Then you use your singleton like this:

    var myInstance = YourClass.singleton();
    

    As of this writing, decorators are not readily available in JavaScript engines. You would need to make sure your JavaScript runtime has decorators actually enabled or use compilers like Babel and TypeScript.

    Also note that singleton instance is created "lazy", i.e., it is created only when you use it for the first time.

提交回复
热议问题