在javascript中还有其他实现单例模式的方法吗?

Is there any other way to implement Singleton Pattern in javascript?

本文关键字:单例模式 方法 实现 其他 javascript      更新时间:2023-09-26

尝试在javascript中实现一些教程中的单例模式。只是想知道是否有其他方法来实现相同的?

var singleton = (function(){
              var getInstance; //private variable
              var createWidget = function(){
                         var todayDate = new Date(); //private
                         var addCSS = function(){
                            console.log('THis is my css function');
                         };
                         var getDropDownData = function(){
                            console.log('This is my getDropDownData function');
                         };
                         return {
                            getDropDownData : getDropDownData,
                            addCSS: addCSS 
                         };
              };
              return {
                    getInstance: function(){
                          if(!getInstance) {
                              getInstance = createWidget();
                          }
                          return getInstance;
                    }
              };
})();
var obj = singleton.getInstance();

通过在onLoad上运行匿名函数并将其赋值给某个变量来实现。

您总是可以编写一个函数来抽象编写单例的样板。例如,我要这样做:

function singleton(prototype) {
    var instance = null;
    return {
        getInstance: function () {
            if (instance === null) {
                var Instance = prototype.init || function () {};
                Instance.prototype = prototype;
                instance = new Instance;
            } return instance;
        }
    };
}

然后你可以使用这个函数创建单例,如下所示:

var Widget = singleton({
    init: function () {
        var todayDate = new Date; // private
    },
    addCSS: function () {
        console.log("This is my addCSS function.");
    },
    getDropDownData: function () {
        console.log("This is my getDropDownData function.");
    }
});

之后像平常一样使用单例:

var widget = Widget.getInstance();

希望对你有帮助。