原型链继承
继承方式
Vip.prototype = new Breast();//原型链继承的核心语句
缺点
- 当原型链中包含引用类型值的原型时,该引用类型值会被所有实例共享;
- 在创建子类型时,不能向超类型的构造函数中传递参数.
借用构造函数继承
继承方式
call执行父构造函数(不是new
), 并绑定this
继承特点:
如同把父构造函数的内容混入子构造函数
// 定义父类
function Breast(sizes_index){
this.sizes = [1100, 1200, 1300] ;
this.sizes_index = sizes_index;
this.show = function () {
breast_image.style.height = this.sizes[sizes_index] + "px";
}
}
// 子类
function Vip(){
Breast.call(this); // 这句代码就是借助构造函数实现部分继承,绑定this并执行父构造函数
}
const vip_G = new Vip();
const vip_H = new Vip();
const vip_I = new Vip();
解决了原型链的两大问题:
- 保证了原型链中引用类型值的独立
- 不再被所有实例共享;子类型创建时也能够向父类型传递参数.
缺点: 如果仅仅借用构造函数,那么将无法避免构造函数模式存在的问题–方法都在构造函数中定义, 因此函数复用也就不可用了. 而且超类型(如Father)中定义的方法,对子类型而言也是不可见的
组合继承
也就是组合上面两种
function Vip(){
Breast.call(this);
}
Vip.prototype = new Breast();
const vip_G = new Vip();
const vip_H = new Vip();
const vip_I = new Vip();
原型式继承
const breast = {
sizes: [1100, 1200, 1300],
};
function object (o) {
function F () {}
F.prototype = o;
return new F ();
}
const vip_G = object (breast);
const vip_H = object (breast);
寄生式继承
寄生组合式继承
是根据前面的借用构造函数,原型式和寄生式继承进行改进的
inheritPrototype(Vip, Breast);
function object (o) {
function F () {}
F.prototype = o;
return new F ();
}
function inheritPrototype(son, father) {
let x = object(father.prototype);
x.constructor = son ;
son.prototype = x;
}