
function Brother(name){

this.name = name;
this.wives = ["奶茶"];
this.marry = function(){};
}
function Employee(name) {
this.name = name;
}
Employee.prototype = new Brother();
優(yōu)點:書寫簡單
缺點: 無法給父類構(gòu)造函數(shù)傳參,子類會繼承父類的所有引用類型,一旦原地修改就會影響所有子類。
const brother = new Brother("劉強(qiáng)東");
const employee1 = new Employee("劉強(qiáng)東的兄弟");
const employee2 = new Employee("劉強(qiáng)東的兄弟2");
console.log(employee1.wives); // 奶茶
console.log(employee2.wives); // 奶茶
employee1.wives.push("綠茶");
console.log(employee1.wives); // 奶茶,綠茶
console.log(employee2.wives); // 奶茶,綠茶
employee1.wives = ["綠茶"]; // 指向不同對象
console.log(employee1.wives); // 綠茶
console.log(employee2.wives); // 奶茶,綠茶
2.借用構(gòu)造函數(shù)
function Brother(name){
this.name = name;
this.wives = ["奶茶"];
this.marry = function(){};
}
function Employee(name, age) {
Brother.call(this, name);
this.age = age;
}
缺點:父類方法內(nèi)的函數(shù)每次都會生成新的拷貝;通過prototype定義的方法無法繼承
3. 組合繼承 (原型鏈 + 借用構(gòu)造函數(shù))
function Brother(name){
this.name = name;
this.wives = ["奶茶"];
}
Brother.prototype.marry = function() {}
function Employee(name, age) {
Brother.call(this, name);
this.age = age;
}
Employee.prototype = new Brother();
缺點: 多次調(diào)用構(gòu)造函數(shù)
4.原型式繼承 duck type 鴨式辨型
function object(o) {
function F(){}
F.prototype = o;
return new F();
}
或者直接object.create(o);
使用場合:沒必要構(gòu)建構(gòu)造函數(shù),僅僅是想模擬一個對象的時候
缺點:同原型鏈
5.寄生繼承
function(original){
newObj = Object(original)
newObj.newFunc =(){}
return newObj
}
缺點:方法在函數(shù)中定義,無法得到復(fù)用
6.寄生組合
function inheritPrototype(subType, supType) {
var p = Object(supType.prototype);
p.constructor = subType;
subType.prototype = p;
}
function subType(){
supType.call(this);
}
inheritProptype(subType, supType)
當(dāng)前標(biāo)題:總結(jié)各種奇葩原型繼承,面試向-創(chuàng)新互聯(lián)
標(biāo)題網(wǎng)址:http://www.chinadenli.net/article30/djdhpo.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供域名注冊、關(guān)鍵詞優(yōu)化、手機(jī)網(wǎng)站建設(shè)、搜索引擎優(yōu)化、建站公司、App開發(fā)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容