原型链:实例指向——构造函数的原型——父对象构造函数的原型——
functionSuperType(){
this.property= true;
}
SuperType.prototype.getSuperValue= function(){
returnthis.property;
}
functionSubType(){
this.subproperty= false;
}
//继承了SuperType
SubType.prototype = new SuperType();
SubType.prototype.getSubValue= function(){
returnthis.subproperty;
}
varinstance = new SubType();
console.log(instance.getSuperValue());
通过这种方式实现继承时,不能用对象字面量创建原型方法,这样会重写原型链。
问题一是包含引用类型值的原型属性会被所有实例共享。二是在创建子类型的实例时,不能向超类型的构造函数中传递参数
借用构造
function SuperType(){
this.colors= ['red','blue','green'];
}
functionSubType(){
SuperType.call(this);
}
varinstance1 = new SubType();
instance1.colors.push('black');
console.log(instance1.colors); //'red,blue,green,black'
varinstance2 = new SubType();
console.log(instance2.colors); //'red,blue,green'函数:
缺点:方法都在构造函数中定义,函数复用就无从谈起了
优点:可以在子类型构造函数中向超类型构造函数传递参数。
组合继承
思路是使用原型链实现对原型属性和方法的继承,而通过借用构造函数来实现对实例属性的继承.但是这种继承会多次调用超类型构造函数而导致低效率问题
functionSuperType(name){
this.name= name;
this.colors= ['red','blue','green'];
}
SuperType.prototype.sayName= function(){
console.log(this.name);
};
functionSubType(name,age){
//继承属性
SuperType.call(this,name);
this.age= age;
}
//继承方法
SubType.prototype= new SuperType();
SubType.prototype.constructor= SubType;
SubType.prototype.sayAge= function(){
console.log(this.name);
}
原型式继承
varperson = {
name:'nina',
friends:['jd','dd','dw']
};
varanotherPerson = Object.create(person);
anotherPerson.name= 'grey';
anotherPerson.friends.push('Rob');
var anotherPerson = Object.create(person,{
name:{
value:’Greg’
}
});
Create接收两个参数(用作新对象原型的对象,一个为新对象定义额外属性的对象)
寄生式继承
function createAnother(o){
var clone = object(o); //通过调用函数创建一个新对象
clone.sayHi =function(){ //以某种方式来增强这个对象
console.log('hi');
};
return clone; //返回这个对象
}
寄生组合式继承
通过借用构造函数来继承属性,通过原型链的混成形式来继承方法
function SuperType(name){
this.name = name;
this.colors =['red','blue','green'];
}
SuperType.prototype.sayName =function(){
console.log(this.name);
}
function SubType(name,age){
SubType.call(this,name);
this.age = age;
}
SubType.prototype= new SuperType();
SubType.prototype.constructor= SubType;
SubType.prototype.sayAge = function(){
console.log(this.age);
}