1<script type= "Text/javascript" >2 //single-case mode3 4 //1, each click will generate a new Div5 varcreatemask=function () {6 returnDocument.body.appendChild (document.createelement (Div));7 }8$ ("button"). Click (function(){9 varmask=Createmask ();Ten mask.show (); One }); A - //2, it's possible that this mask will never be used. - varMask=document.body.appendchild (Document.createmask ("div")); the$ ("button"). Click (function(){ - mask.show (); - }); - + //3,1) function changes the reference of the variable mask in the body, Createmask is an unsafe function in a multi-person collaborative project. 2) on the other hand, mask this global variable is not necessary. - varMask; + varcreatemask=function(){ A if(mask) { at returnMask; - } - Else{ -mask=Document.body.appendChild (document.createelement (Div)); - returnMask; - } in }; - //4, in the form of closures, only a mask is generated to varcreatemask=function(){ + varMask; - return function(){ the returnmask| | (mask=Document.body.appendChild (document.createelement (div))); * }; $ }()Panax Notoginseng //5, final version - varsingleton=function(FN) { the varresult; + return function(){ A returnresult| | (Result=fn.apply ( This, arguments)); the } + } - varCreatemask=singleton (function(){ $ returnDocument.body.appendChild (document.createelement ("div")); $ }); - A variable is used to hold the return value for the first time, and if it has already been assigned a value, in a subsequent call, the value is returned first, -</script>
JS design mode Note 1, single-case mode