继承

JavaScript继承

原型继承,问题:如果父类有引用类型,实例都会共享这引用类型

1
2
3
4
5
6
7
8
9
function SuperType(){
this.basic = 'basic';
this.refer = [1,2,3,4,5]
}

function SubType(){}

SubType.prototype = new SuperType();
SubType.prototype.constructor = SubType;

为了解决这个问题,发明了借用构造函数,这样每个实例都有自己引用属性了

1
2
3
4
5
6
7
8
function SuperType(){
this.refer = [1,2,3,4,5]
}
SubType.prototype = new SuperType();
SubType.prototype.constructor = SubType;
function SubType(){
SuperType.call(this)
}

都继承了父类,函数复用就无从说起,于是发明了组合继承

调用构造函数继承实例属性,在子类定义原型方法

1
2
3
4
5
6
7
8
function SuperType(){}

function Subtype(){
SuperType.call(this)
}
SubType.prototype = new SuperType();
SubType.prototype.constructor = SubType;
SubType.prototype.someMethod = function(){}

原型式继承,父类引用属性也会共享

1
2
3
4
5
6
7
8

function creatFromObject(parent){
function F(){}
F.prototype = parent;
return new F();
}

let child = creatFromObject({});

寄生式继承,不能做到函数复用

1
2
3
4
5
function createAnother(parent){
var clone = creatFromObject(parent);
clone.someMethod = function(){}
return clone;
}

寄生组合继承(避免构造函数执行2次)

1
2
3
4
5
function inherit(SubType, SuperType){
let prototype = creatFromObject(SuperType.prototype)
prototype.constructor = Subtype;
Subtype.prototype = prototype;
}