继承
接口继承——继承方法签名(接受的参数的类型和数量)
实现继承——继承实际的方法(原型链)
原型链
原型链:让原型对象等于另一个对象的实例
function SuperType(){ this.colors=["red","blue","green"]; } function SubType(){} //继承SuperTyper SubType.prototype=new SuperType(); var instance1=new SubType(); instance1.colors.push("black"); alert(instance1.colors); //""red,blue,green,black" var instance2=new SubType(); alert(instance2.colors); //""red,blue,green,black"
缺陷:原先的实例属性变成了新对象的原型属性,原型属性会被所有实例共享
另外在创建子类型的实例时,不能向超类型的构造函数中传递参数
借用构造函数
借用构造函数——在子类型构造函数的内部调用超类型构造函数
function SuperType(){ this.colors=["red","blue","green"]; } function SubType(){ //继承SuperType SuperType.call(this); } var instance1=new SubType(); instance1.colors.push("black"); alert(instance1.colors); //""red,blue,green,black" var instance2=new SubType(); alert(instance2.colors); //"red,blue,green,"
缺陷:方法都在构造函数中定义,不存在函数复用
组合继承
原型链——实现对原型属性和方法的继承
借用构造函数——实现对实例属性的继承
function SuperType(name){
this.name=name;
this.colors=["red","blue","green"];
}
SuperType.prototype.sayName=function(){
alert(this.name);
}
function SubType(name,age){
//继承S属性
SuperType.call(this,name);
this.age=age;
}
//继承方法
SubType.prototype=new SuperType();
SubType.prototype.constructor=SubType;
SubType.prototype.sayAge=function(){
alert(this.age);
}
var instance1=new SubType("Nicholas",29);
instance1.colors.push("black");
alert(instance1.colors); //""red,blue,green,black"
alert(instance1.sayName); //"Nicholas
alert(instance1.sayAge); //29
var instance2=new SubType("Greg",27);
alert(instance2.colors);//""red,blue,green,"
alert(instance2.sayName); //Greg
alert(instance2.sayAge); //27
原型式继承
var person={
name:"Nicholas",
friends:["Shelby","Court","Van"]
};
var anotherPerson=Object.create(person,{
name:{
value:"Greg"
}
});
alert(anotherPerson.name); //"Greg"
寄生式继承
function createAnother(original){
var clone=Object(original);
clone.sayHi=function(){
alert("hi");
};
return clone;
}
var person={
name:"Nicholas",
friends:["Shelby","Court","Van"]
};
var anotherPerson=createAnother(person);
anotherPerson.sayHi();
寄生组合式继承
构造函数——继承属性
原型链——继承方法
function inheritPrototype(subType,superType){
var prototype=Object(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.cal(this.name);
this.age=age;
}
inheritPrototype(SubType,SuperType);
SubType.prototype.sayAge=function(){
alert(this.age);
};