es5的类(es5是没有类,口头习惯)继承有七八中,但常用三种够用了
1. 原型链
缺点:父类的实例属性变成子类的原型属性
function SuperType() {
this.name ='liangcheng';
}
SuperType.prototype.sayName = function () {}
function SubType() {
this.subname = 'xushizhou';
}
// 继承
SubType.prototype = new SuperType();
SubType.prototype.getSubValue = function (){
return this.subname ;
};
2. 借用构造
缺点:没继承原型属性
function SuperType(){
this.colors = ["red", "blue", "green"];
}
function SubType(){
SuperType.call(this);
}
3. 动态组合继承
将上面的两个缺点进行弥补
function Parent3(){
this.name = "parent3";
this.play = [1,2,3];
}
function Child3(){
Parent3.call(this);
this.type = "child3";
}
Child3.prototype = Object.create(Parent3.prototype);
Child3.prototype.constructor = Child3;
ps: Child3.prototype = Parent3.prototype;
,原因是,如果这样,Child3.prototype.constructor = Child3;
相当于把父类的cunstructor
修改了。【Object.create()说明】