组合继承与寄生继承
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的属性, 略微复杂, 可以忽略不计, 完美方式