組合繼承與寄生繼承
function Parent(name){
this.name = name;
this.methods = function(){
console.log("do someThing")
}
}
組合繼承
function Children(name){
Parent.call(this); // 1. 拷貝屬性
this.name = name || 'zhangsan';
}
Children.prototype = new Parent(); //2. 原型指向父類實例
Children.prototype.constructer = Children; 3. 修正constructor 指向
- 可以繼承實例屬性和方法,也可以繼承原型屬性和方法
- 是子類實例,也相當于父類實例
- 子類原型指向父類實例,該父類實例又可以向上原型查找訪問,修正constructor指向子類自身
- 可傳參,call 方法可傳參
- 調用兩次父類構造函數, 占內存, 第一步拷貝過一次, 第二步導致以后的Jianren的實例里和Jianren原型上重復的屬性
寄生組合類型
function Children(name){
Parent.call(this); // 1. 拷貝屬性
this.name = name || 'zhangsan';
}
(function(){
function Storage(){} // 創建一個中間類,空
Storage.prototype = Paren.prototype; //將中間類指向父類原型
Children.prototype = new Storage(); //子類原型賦值中間類實例,往上查找,指向父類的原型
})()
Children.prototype.constructor = Children; // 修正子類constructor指向
與上面的組合繼承相比, 第一步拷貝 和 第二步中間類(空類)不會重復有Human的屬性, 略微復雜, 可以忽略不計, 完美方式