Definition: Ensure that a class has only one instance and provides a global interface for access:
is to accept: when we var a = new A (); var a1 = new A () is; A is equal to A1. How to achieve it, is the first time instantiation. The second is not the instance, but the first instantiation is returned:
Attach the general inertia Singleton idea:
Singleton.getinstance = (function () { var instance = null; return function (name) { if (!instance) { instance = new Singleton (name); } return instance; }}) ()
Example of a login box on a book:
varCreateloginlayer =(function () {varDiv; returnfunction () {if(!Div) {Div= Document.createelement ('Div'); Div.innerhtml='I am a login'; Div.style.display='None'; Document.body.appendChild (DIV); } returnDiv; }}) () document.getElementById ('Div1'). onclick =function () {varLoginlayer =Createloginlayer (); LoginLayer.style.display='Block'; }
General-purpose Inert single cases:
varGetsingle =function (FN) {varresult; returnfunction () {returnResult | | (Result = Fn.apply ( This, arguments)); }}varCreateloginlayer =function () {vardiv = document.createelement ('Div'); Div.innerhtml='Woshi Denglu'; Div.style.display='None'; Document.body.appendChild (DIV); returnDiv;}varCreatesingleloginlayer =Getsingle (Createloginlayer); document.getElementById ('Div1'). onclick =function () {varLoginlayer =Createsingleloginlayer (); LoginLayer.style.display='Block'; } //when creating a unique iframe varCreatesingleframe =Getsingle (function () {variframe = document.createelement ('iframe'); Document.body.appendChild (IFRAME); returniframe; }) document.getElementById ('Div1'). onclick =function () {varLoginlayer =Createsingleframe (); LOGINLAYER.SRC='http://baidu.com' }
JavaScript design mode 1----Singleton mode