标签:style blog http color os io strong ar div
单体是一个用来划分命名空间并将一批相关的属性和方法组织在一起的对象,如果他可以被实例化,那么他只能被实例化一次。
特点:
/*Basic Singleton*/ var Singleton = { attribute1:true, attribute2:10, method1:function(){}, method2:function(){} };
var box = { width:0, height:0, getArea:function(){ return this.width*this.height;//js中对象成的访问必须是显示的,即this是不能省略的,报错 }, init:function(w,h){ // width = w; // height = h;这种方式相当于定义了两个全局变量,(没加var声明的变量为全局变量) // 并不是对对象width和height的赋值 //下面是正确的 this.width = w; this.height = h; } }//box划分了一个命名空间,命名空间里的变量只在空间里有效
var box = { width:0, height:0, getArea:function(){ return width*height; }, init:function(w,h){ width = w; height = h; } } window.onload = function(){ width = 0; height = 0; //or box.init(0,0); var init = box.getArea(); alert(init); }
var circle = (function(){ //pravite member! var r = 5; var pi = 3.1416;//后面用分号 return{//public member getArea:function(){ return r*r*pi;//访问私有成员不要加this },//后面用逗号 //如果想改变r和pi的值,只能通过设置一个公有的函数来实现 init:function(setR){ r = setR; } } })() window.onload = function(){ circle.r = 0;//无法访问私有成员,相当于又为circle创建了一个共有成员r alert(circle.getArea()); circle.init(0);//通过公有的工具函数便可以访问了。 alert(circle.getArea()); };
// 利用单体的分支技术来定义XHR(XMLHttpRequest)对象,必须要用闭包才可以实现 var XHR = (function(){ //The three branches var standard = { cXHR:function(){ return new XMLHttpRequest(); } }; var activeXNew = { cXHR:function(){ return new ActiveXObject(‘Msxml2.XMLHttp‘); } }; var activeXOld = { cXHR:function(){ return new ActiveXObject(‘Microsoft.XMLHttp‘); } }; //To assign(分配) the branch, try each method;return whatever doesn‘t fail var testObject; try{ testObject = standard.cXHR(); return standard;// return this branch if no error was thrown }catch(e){ try{ testObject = activeXNew.cXHR(); return activeXNew; }catch(e){ try{ testObject = activeXOld.cXHR(); return activeXOld; }catch(e){ throw new Error(‘Create the XMLHttpRequestObject failed!‘); } } } })(); window.onload = function(){ alert(XHR.cXHR()); }
标签:style blog http color os io strong ar div
原文地址:http://www.cnblogs.com/Watcher/p/3934534.html