關(guān)于Js繼承的幾種方式,總結(jié)一下,以便查看。
第一種 prototype 引用型原型繼承
語言支持:js原生支持的繼承方式 構(gòu)造器的的prototype屬性作為類的原型 每個該類的對象都持有一個到原型的引用 當(dāng)對象中的屬性不存在時 可以訪問原型的屬性
代碼示例:
function parent(){
? ? ? this.x=10;
}
function child(){
}
child.prototype=new parent();
var childObj=new child();
alert(childObj.x);
第二種 復(fù)制型原型繼承
語言支持:js new運算符的性質(zhì) 當(dāng)構(gòu)造函數(shù)return值為非空對象時 new表達(dá)式返回return的對象
代碼示例:
function parent(){
? ? ? ? this.x=10;
}
function child(){
? ? ? var ret=new parent();
? ? ? ret.y=20;
? ? ? return ret;
}
var childObj=new child();
alert(childObj.x);
第三種 類繼承 屬性抄寫
語言支持:for in枚舉對象所有屬性
代碼示例:
function parent(){
? ? ? ? this.x=10;
}
function child(){
? ? ? var parentObj=new parent();
? ? ? for(var p in parentObj){
? ? ? ? ? ? ? this[p]=parentObj[p];
? ? ? }
}
var childObj=new child();
alert(childObj.x);
第四種 類繼承 對象冒充
語言支持:
1.動態(tài)添加和刪除方法
2.函數(shù)的call和apply
代碼示例:
function parent(){
? ? ? ? this.x=10;
}
function child(){
? ? ? ? this.parent=parent;
? ? ? ? this.parent();
? ? ? ? delete this.parent;
}
var childObj=new child();
alert(childObj.x);
function parent(){
? ? ? ? this.x=10;
}
function child(){
? ? ? ? ? parent.call(this);
}
var childObj=new child();
alert(childObj.x);
第五種 原型抄寫
語言支持:通過修改類的原型對象 可以為一類對象添加屬性和方法
代碼示例:
function parent(){}
parent.prototype.me=function(){
? ? ? ? alert("parent")
};
function child(){}
for(var p in parent.prototype){
? ? ? ? ? ? ? ? child.prototype[p]=parent.prototype[p];
}
var childObj=new child();
childObj.me();
第六種 元類
語言支持: js函數(shù)都是對象 且js函數(shù)可被構(gòu)造
代碼示例:
function parent(string){
? ? ? ? var child=new? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? Function("this.x=10;"+string);? ?
? ? ? ? return child;
}
var child=new parent("this.y=20;");
var childObj=new child();
alert(childObj.y);