Simplest/Cleanest way to implement singleton in JavaScript?

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

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

30条回答
  •  庸人自扰
    2020-11-22 05:35

    I deprecate my answer, see my other one.

    Usually module pattern (see CMS' answer) which is NOT singleton pattern is good enough. However one of the features of singleton is that its initialization is delayed till object is needed. Module pattern lacks this feature.

    My proposition (CoffeeScript):

    window.singleton = (initializer) ->
      instance = undefined
      () ->
        return instance unless instance is undefined
        instance = initializer()
    

    Which compiled to this in JavaScript:

    window.singleton = function(initializer) {
        var instance;
        instance = void 0;
        return function() {
            if (instance !== void 0) {
                return instance;
            }
            return instance = initializer();
        };
    };
    

    Then I can do following:

    window.iAmSingleton = singleton(function() {
        /* This function should create and initialize singleton. */
        alert("creating");
        return {property1: 'value1', property2: 'value2'};
    });
    
    
    alert(window.iAmSingleton().property2); // "creating" will pop up; then "value2" will pop up
    alert(window.iAmSingleton().property2); // "value2" will pop up but "creating" will not
    window.iAmSingleton().property2 = 'new value';
    alert(window.iAmSingleton().property2); // "new value" will pop up
    

提交回复
热议问题