JS封裝繼承函數

來源:互聯網
上載者:User

標籤:

 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封裝繼承函數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.