JS的常见继承:
1,原型链继承(对象间的继承):
function Person() {
this.name = "CRR";
}
function Chinese(){
this.age = 18;
}
Chinese.prototype = new Person();
var CRR = new Chinese();
console.log(CRR.age + "+" + CRR.name);//得到被继承的属性;
确定原型与实例的关系,instanceof 和isPrototypeof()
只要是原型链中出现过的原型,都可以说是该原型链派生的实例的原型。
被继承的函数被称为超类型(父类,基类),继承的函数称为子类型(子类,派生),原型继承主要存在的问题:
1,字面量重写会与原型中断关系,使用引用类型的原型;2,子类型无法给超类型传参。
2,构造函数继承,类式继承
function Parent(age) {
this.name = ["mike","jack","simth"];
this.age = age;
}
function children(age) {
Parent.call(this,age);
}
var test = new children(21);
console.log(test.age);
借用构造函数,使用call方法,虽然解决了传参的问题,但是没有原型,无法复用;
3,组合继承(原型链+借用构造函数)
function Parent(age) {
this.name = ["mike","jack","simth"];
this.age = age;
}
Parent.prototype.run = function () {
return this.name+ "are both" + this.age;
}
function Child(age) {
Parent.call(this,age);
}
Child.prototype = new Parent();
就是在子类中使用call调用父类构造函数,同时将子类的prototype指向父类的实例;
使用原型链实现对原型属性和方法的继承,而通过借用构造函数来实现对实例属性的继承。