1 /*2 1 Simple monomers3 */4 varSingleton = {5Attr1:1 ,6METHOD1:function(){7 //Do sth8 }9 };Ten alert (SINGLETON.ATTR1); One singleton.method1 (); A - //The monomer pattern is typically used to divide the namespace, which is the code that distinguishes which developer - //code developed by Zhang San engineers the varZhangsan = { }; - //write the logic of Zhang San in here. -Zhangsan.singleton = { -Attr1:1, +METHOD1:function(){ - //Do sth + } A }; at - - - - /* - 2 closure monomers: Closures The main purpose is to protect private variable data in */ - //name Space to varZhangsan = {}; +Zhangsan.singleton = (function(){ - //private variables and methods the varA = 1; * functionf () { $ //Do sthPanax Notoginseng } - //returns the Monomer object the return { + Attr1:a, AMETHOD1:function(){ the returnf (); + } - }; $ })(); $ alert (ZHANGSAN.SINGLETON.ATTR1); - Zhangsan.Singleton.method1 (); - the /* - 3 inert monomers: (similar to the closure monomers)Wuyi */ the - varZhangsan = {}; WuZhangsan.singleton = (function(){ - //Private variable controls the returned monomer object About varuniqinstance; $ //Initialize method to control what is in the returned monomer . - functioninit () { - //Private Variables - varA = 10; A varfn =function(){ +Alert ("FN"); the }; - return { $ attr:a, the METHOD:FN the }; the } the - return { inGetInstance:function(){//If there is a monomer then return otherwise create a return the if(!uniqinstance) {//If it does not exist theUniqinstance =init (); About } the returnuniqinstance; the } the }; + })(); - the //Calling Lazy monomersBayiAlert (Zhangsan.Singleton.getInstance (). attr);//Ten theZhangsan.Singleton.getInstance (). method ();//fn the - - the /* the 4 branching monomers: Judging the difference detection of the program branch browser the */ the varZhangsan ={}; - vardifferent =true;//used to mark different browsers theZhangsan.singleton = (function(){ the varObja = {//a browser's internal configuration the //properties, methods, and so on94attr: "A", theMethod:function(){ theAlert ("FN"); the }98 }; About varOBJB = {//b browser's internal configuration - //properties, methods, and so on101 };102 return(different)? OBJA:OBJB;//different objects are returned depending on the browser103 })();104 thealert (Zhangsan.Singleton.attr);//a
Four ways to implement the monomer pattern in JavaScript