1.原型链
function SuperType(){
this.property = true;
}
SuperType.prototype.getSuperValue = function(){
return this.property;
};
function SubType(){
this.subproperty = false;
}
SubType.prototype = new SuperType();
将SuperType的实例作为SubType的原型,从而构成原型链。
注意:
给原型添加方法(重写原型方法)的代码一定要放在替换原型的语句之后。
不能用对象字面量创建原型方法,会导致重写原型链。
包含引用类型值的原型属性会被所有实例共享。
无法给超类的构造函数传递参数。
2.借用构造函数
funtion SuperType(){
}
function SubType(){
SuperType.call(this);
}
子类型构造函数可向超类型构造函数传递参数
funtion SuperType(name){
this.name = name
}
function SubType(){
SuperType.call(this,"name");
this.age = 1;
}
因为方法都在构造函数中定义,无法函数复用。
超类型的原型中定义的方法对子类型也是不可见的
3.组合继承
funtion SuperType(name){
this.name = name
}
SuperType.prototype.sayName= function(){
alter(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(){
alter(this.age);
};
调用了两次超类型构造函数。
4.原型式继承
var person = {};
var anotherPerson = object(person);
es5增加的Object.create()
var anotherPerson = Object.create(person, {
name:{
value: "name"
}
});
5.寄生式继承
function creatAnother(original){
var clone = object(original);
clone.sayHi = function(){};
return clone;
}
6.寄生组合式继承
function inheritPrototype(subType,superType){
var prototype = object(superType.prototype);
prototype.constructor = subType;
subType.prototype = prototyep;
}
funtion SuperType(name){
this.name = name
}
function SubType(name, age){
SuperType.call(this,name);
this.age = age;
}
inheritPrototype(SubType,SuperType);
SubType.prototype.sayAge= function(){
alter(this.age);
};
只调用了一次SuperType构造函数。