標籤:
1 function extend(child,parent){ 2 var F=function(){} 3 F.prototype=parent.prototype; 4 child.prototype=new F(); 5 child.prototype=child; 6 child.uber=parent.prototype; //uber指向父物件的原型。方便子物件調用父物件原型中的重寫的方法。 7 } 8 function Shape(){} 9 Shape.prototype.name="Shape";10 Shape.prototype.color="blue";11 12 function circle(radius){13 this.radius=radius;14 }15 16 circle.prototype.name="circle";17 circle.prototype.getS=function(){18 return this.radius*this.radius*3.14;19 }20 extend(circle,Shape);21 22 var cir=new circle(2);23 alert(cir.name); //"circle"24 alert(cir.color); //"blue"25 alert(cir.uber.name); //"Shape"26 alert(cir.getS()) //"12.56"
extend函數的第一個參數是子構造器,第二個參數是父構造器;
為什麼子構造器的原型對象不直接指向父構造器的原型對象,是因為若child.prototype=parent.prototype,則會出現父子的原型對象綁定在一起,即父子的原型對象的引用相等,相當於指向同一個地址,改變子物件的原型,父物件的原型也會隨之改變,若遍曆父物件的原型和子物件的原型,發現兩個完全相同個。
1 var cir=new circle(2); 2 var shape1=new Shape(); 3 cir.prototype.name="this is circle"; 4 5 6 for(var i in shape1){ 7 if(!shape1.hasOwnProperty(i)){ //遍曆非執行個體屬性 8 console.log(i+":"+shape1[i]); 9 }10 }11 12 //name:circle13 //color:blue14 //getS:function (){15 return this.radius*this.radius*3.14;16 }17 18 19 for(var i in cir){20 if(!cir.hasOwnProperty(i)){21 console.log(i+":"+cir[i]);22 }23 }24 25 //name:circle26 //color:blue27 //getS:function (){28 return this.radius*this.radius*3.14;29 }.
JS封裝繼承函數