原型链继承
function SuperType(){
this.property=true;
}
SuperType.prototype.getSuperValue=function(){
return this.property;
}
function SubType(){
this.subproperty=false;
}
SubType.prototype=new SuperType();
SubType.prototype.getSubValue=function(){
return this.subproperty;
}
var instance=new SubType();
console.log(instance.getSuperValue());//true
问题:
第一:引用类型的原型属性会被所有实例共享
第二:在创建子类型的实例时,不能像超类型的构造函数中传递参数
借用构造函数
function Parent(){
this.colors=['red','green'];
}
function Child(){
// 继承
Parent.call(this);
}
var instance1=new Parent();
instance1.colors.push('blue');
var instance2=new Parent();
console.log(instance2.colors);//["red", "green"]
特点:
第一:可以在子类型构造函数像向超类型构造函数传递参数
第二:函数复用无从谈起
组合继承
使用原型链实现对原型属性和方法的继承,通过借用构造函数来实现对实例属性的继承
function SuperType(name){
this.name=name
this.colors=['red','green'];
}
SuperType.prototype.sayName=function(){
console.log(this.name);
}
function SubType(name,age){
SuperType.call(this,name);
this.age=age;
}
SubType.prototype=new SuperType();
SubType.prototype.constructor=SubType
SubType.prototype.sayAge=function(){
console.log(this.age);
}
var s1=new SubType('didi',5);
s1.colors.push('blue');
s1.sayAge();
s1.sayName();
console.log(s1.colors);
var s2=new SubType('jiejie',8);
console.log(s2.colors);
原型式继承
function object(o){
function F(){};
F.prototype=o;
return new F();
}
var person={
name:'xiaoxiao',
friends:['didi','jiejie']
}
var p1=object(person);
p1.name='yaya';
p1.friends.push('gege');
var p2=object(person);
p2.name='wenwen';
p2.friends.push('meimei');
console.log(person.friends);//["didi", "jiejie", "gege", "meimei"]
寄生式继承
创建一个引用于封装继承过程的函数,该函数在内部以某种方式来增强对象
function object(o){
function F(){};
F.prototype=o;
return new F();
}
function createAnother(original){
var clone=object(original);
clone.sayHi=function(){
console.log('hi');
}
return clone;
}
var person={
name:'xiaoxiao',
friends:['didi','jiejie']
}
var p1=createAnother(person);
p1.sayHi();//'hi'
寄生组合式继承
通过借用构造函数来继承属性,通过原型链的混成形式来继承方法,思路是:不必为了指定子类型的原型而调用超类型的构造函数,需要的是超类型的一个副本。本质是个就是使用寄生式继承来继承超类型的原型,然后再将结果指定给子类型的原型。
function object(o){
function F(){};
F.prototype=o;
return new F();
}
function inheritPrototype(subType,superType){
var prototype=object(superType.prototype);
prototype.constructor=subType;
subType.prototype=prototype;
}
function SuperType(name){
this.name=name
this.colors=['red','green'];
}
SuperType.prototype.sayName=function(){
console.log(this.name);
}
function SubType(name,age){
SuperType.call(this,name);
this.age=age;
}
inheritPrototype(SubType,SuperType);
SubType.prototype.sayAge=function(){
console.log(this.age);
}
var p1=new SubType('lili',5);
p1.sayAge();//5
p1.sayName();//'lili'