標籤:對象 png nbsp 技術 組合模式 模式 end 調用 方式
參考文檔:JS原型繼承和類繼承
<script src="jquery-2.0.3.js"></script><script>/*//類繼承 var father=function(){ this.age=53; this.say=function(){ console.log("name:"+this.name+",age:"+this.age); } }; var child=function(){ this.name="child"; father.call(this); } var man=new child(); man.say();
console.log(man); */ //原型繼承 var father=function(){} father.prototype.a=function(){console.log(11)}; var child=function(){}; child.prototype=new father(); var man=new child(); man.a(); console.log(man);</script>
類繼承時列印man:
原型繼承時列印man:
看似,原型繼承時,對象可以調用原型上的方法
類繼承的方法,每一次都會存到記憶體中,損耗效能,並且不容易擴充
原型繼承:很靈活,改變原型鏈即可,寫好extend就可以
通常繼承會匯聚兩種方式的優點,組合模式就是這樣做:用類繼承去繼承屬性(每個執行個體的屬性應該是私人的,不應該是共有的),用原型繼承去繼承方法
例如
var father=function(){ this.age=53; }; father.prototype.b=new function(){ console.log(this.age); } var child=function(){ father.call(this); }child.prototype=new father();var man=new child();console.log(man);
**使用 Object.create()
var father ={ a:‘father‘, b:function(){ console.log(this.a); }}var obj=Object.create(father);console.dir(obj);
JS 類繼承 原型繼承