原型鏈+借用構(gòu)造函數(shù)的組合繼承
function parent(val){
this.val=val;
}
parent.prototype.getvalue=function(){
console.log(this.val);
}
function Child(val){
parent.call(this,val);
}
Child.prototype=new parent();
var child=new Child(1);
child.getvalue();
console.log(child instanceof parent);
在子類的構(gòu)造函數(shù)中通過parent.call(this)
繼承父類的屬性披摄,然后改變子類的原型為new parent()
來繼承父類函數(shù)。
這種繼承的方式龄句,優(yōu)點在于構(gòu)造函數(shù)可以傳參近她,不會與父類引用屬性共享试浙,可以復(fù)用父類的函數(shù)折联,缺點是繼承父類函數(shù)的時候調(diào)用父構(gòu)造函數(shù)官脓,導(dǎo)致子類的原型上多了不需要的父類屬性仿贬,存在內(nèi)存浪費茁瘦。
寄生組合繼承(優(yōu)化上一種組合繼承)
function parent(val){
this.val=val;
}
parent.prototype.getvalue=function(){
console.log(this.val);
}
function Child(val){
parent.call(this,val);
}
//Object.create()方法創(chuàng)建一個新對象品抽,使用現(xiàn)有的對象來提供新創(chuàng)建的對象的__proto__。
Child.prototype=Object.create(parent.prototype,{
constructor:{
value:Child,
enumerable:false,
writable:true,
configurable:true
}
});
var child=new Child(1);
child.getvalue();
console.log(child instanceof parent);
將父類的原型賦值給子類甜熔,即解決了無用的父類屬性問題圆恤,正確找到子類的構(gòu)造函數(shù)。
ES6中class繼承
class可以通過extends關(guān)鍵字實現(xiàn)繼承腔稀,還可以通過static關(guān)鍵字定義類的靜態(tài)方法盆昙。class關(guān)鍵字只是原型的語法糖,js繼承依舊是基于原型實現(xiàn)的焊虏。
class parent{
constructor(val){
this.val=val;
}
getvalue(){
console.log(this.val);
}
}
class Child extends parent{
constructor(val){
super(parent);
this.val=val;
}
}
var child=new Child(1);
child.getvalue();
console.log(child instanceof parent);
function inheritPrototype(subType, superType){
var prototype = Object.create(superType.prototype); //創(chuàng)建對象
prototype.constructor = subType; //增強對象
subType.prototype = prototype; //指定對象
}
class實現(xiàn)繼承核心在于使用extends表明繼承自哪個父類淡喜,并且在子類構(gòu)造函數(shù)中必須調(diào)用super,因為類似parent.call(this,val)
诵闭。