原型鏈繼承
原型鏈繼承缺點(diǎn):
1 子類從父類繼承的屬性和方法變成了共享的
2 繼承時(shí)子類無(wú)法給父類傳遞參數(shù)
function Box() { //Box 構(gòu)造
this.name = 'Lee';
}
function Desk() { //Desk 構(gòu)造
this.age = 100;
}
Desk.prototype = new Box(); //Desc 繼承了Box,通過原型,形成鏈條
var desk = new Desk();
alert(desk.age);
alert(desk.name); //得到被繼承的屬性
function Table() { //Table 構(gòu)造
this.level = 'AAAAA';
}
Table.prototype = new Desk(); //繼續(xù)原型鏈繼承
var table = new Table();
alert(table.name); //繼承了Box 和Desk
原型鏈繼承流程圖
在JavaScript 里,被繼承的函數(shù)稱為超類型(父類,基類也行,其他語(yǔ)言叫法),繼承的
函數(shù)稱為子類型(子類,派生類)。繼承也有之前問題,比如字面量重寫原型會(huì)中斷關(guān)系,使
用引用類型的原型,并且子類型還無(wú)法給超類型傳遞參數(shù)。
對(duì)象冒充
缺點(diǎn):無(wú)法繼承父類的原型屬性與方法
優(yōu)點(diǎn):可以向父類傳參
function Box(age) {
this.name = ['Lee', 'Jack', 'Hello']
this.age = age;
}
function Desk(age) {
Box.call(this, age); //對(duì)象冒充,給超類型傳參
}
var desk = new Desk(200);
alert(desk.age);
alert(desk.name);
desk.name.push('AAA'); //添加的新數(shù)據(jù),只給desk
alert(desk.name);
組合繼承(原型鏈繼承+對(duì)象冒充)
function Box(age) {
this.name = ['Lee', 'Jack', 'Hello']
this.age = age;
}
Box.prototype.run = function () {
return this.name + this.age;
};
function Desk(age) {
Box.call(this, age); //對(duì)象冒充 繼承父類構(gòu)造函數(shù)里的實(shí)例屬性 并可以向父類傳遞參數(shù)
}
Desk.prototype = new Box(); //原型鏈繼承 繼承父類的原型屬性與方法
var desk = new Desk(100);
alert(desk.run());