Javascript 单例模式

Javascript singleton pattern

本文关键字:单例模式 Javascript      更新时间:2023-09-26

我不知道如何解释我面临的问题。我做了一个小片段。请检查以下内容:

var Package = {};
Object.defineProperty(Object.prototype, 'inherit',
    {
        value: function(Parent, args)
        {
            var temp = function(){};
            temp.prototype = Parent.prototype;
            this.prototype = new temp();
            this.uber = Parent.prototype;
            this.prototype.constructor = this;
        },
        enumerable: false
    });
var Module1 = Package.Module1 = function() {
  // code;
};
Module1.prototype.method1 = function() {
};

var Module2 = Package.Module2 = function() {
  // code;
};
Module2.prototype.method2 = function() {
};

var Module3 = Package.Module3 = function() {
  // code;
};
// using custom : object.prototype.inherit
// Module3 inherit Module1 and 2;
Module3.inherit(Module1);
Module3.inherit(Module2);
Module3.prototype.method3 = function() {
};
//creating object 
var mod = new Package.Module3();
mod.method1();
mod.method2();
mod.method3();

创建 mod 对象,我可以访问方法1、2 和 3。但实际上我想在不创建对象的情况下调用方法,例如 Package.Module3.method1();怎么可能?

对象文字表示法?

var Package = {
    ModuleA : {
        methodA : function(){},
        methodB : function(){}
    },
    ModuleB : {
        methodC : function(){},
        methodD : function(){}
    }
}
Package.ModuleA.methodA();

尝试这样的事情:

var Module3 = Package.Module3 = (function() {       
   var Module3 = function(){
       // using custom : object.prototype.inherit
       // Module3 inherit Module1 and 2;
   };
   Module3.inherit(Module1);
   Module3.inherit(Module2);
   Module3.prototype.method3 = function() {
   };
   return new Module3();
})();

在这种情况下,您只有一个类Module3实例。

用法

Package.Module3.method1();
Package.Module3.method2();
Package.Module3.method3();