js 继承
- 原型链继承
构造函数、原型和实例之间的关系:每个构造函数都有一个原型对象,每个实例对象都会有个__proto__,指向构造函数的protoType , :获取对象的原型对象 getPrototypeOf
本质,修改原有构造函数的prototype 指向需继承的对象 。缺点:继承对象修改获取改变实例对象
function Father(){
this.isFang = true
}
function Sub(){
this.x = 1
}
Sub.prototype = new Father()
- 借用构造函数,等于复制父类给子类
function Father(){
this.isFang = true
}
function Sub(){
Father.call(this)
}
相对于 在Sub(){Objct.assign(this,new Father())},, 不能继承原型方法
- 组合继承
原型链+构造函数
function Father(){
this.isFang = true
}
function Sub(){
Father.call(this)
}
Sub.prototype = new Father()
- 原型式继承 利用一个空对象为中介,将某个对象直接赋值给空对象构造函数的原型
- 寄生式继承
- 寄生组合
function inheritPrototype(subType, superType){
var prototype = Object.create(superType.prototype);
prototype.constructor = subType;
subType.prototype = prototype;
function SuperType(name){ this.name = name; this.colors = ["red", "blue", "green"]; }
SuperType.prototype.sayName = function(){ alert(this.name); };
function SubType(name, age){ SuperType.call(this, name); this.age = age; }
inheritPrototype(SubType, SuperType);
SubType.prototype.sayAge = function(){ alert(this.age); }
var instance1 = new SubType("xyc", 23);
var instance2 = new SubType("lxy", 23);
instance1.colors.push("2");
- class 继承