静态:共享
一、公有静态成员作为函数的属性即可):
1 var Gadget = functionprice) { 2 this.price = price; 3 } 4 Gadget.isShiny = function){ 5 var msg = 'you bet';//公有静态 6 ifthis instanceof Gadget){//实例调用时 7 msg += ', it costs ' + this.price + '!'; 8 } 9 return msg; 10 } 11 Gadget.prototype.isShiny = function){ 12 return Gadget.isShiny.callthis) 13 } 14 15 console.logGadget.isShiny));//you bet 此为静态调用 16 var a = new Gadget23); 17 console.loga.isShiny));//you bet, it costs 23! 此为实例调用
二、私有静态成员:
私有:构造函数外部不可访问
静态:所有实例共享
通过即时函数创建作用域存放
1 var Person; 2 function){ 3 var id = 0;//私有 4 Person = function){ 5 id ++; 6 this.id = id; 7 } 8 Person.prototype.getId = function){ 9 console.logthis.id); 10 } 11 Person.prototype.getLastId = function){ 12 console.logid); 13 } 14 15 })); 16 17 18 var p1 = new Person); 19 p1.getLastId);//1 20 p1.getId);//1 21 22 var p2 = new Person); 23 p2.getLastId);//2 24 p2.getId)//2 25 26 var p3 = new Person); 27 p3.getLastId);//3 28 p3.getId);//3 29 30 31 p1.getId);//1 32 p2.getId);//2 33 p3.getId);//3
注:JavaScript设计 P108-111 略变
