基本结构
function Suaa(){
//Suaa构造函数自定义属性
this.pro1=true;
}
//给Suaa构造函数添加原型对象方法
Suaa.prototype.get1=function(){
return this.pro1;
};
function Subb(){
//Subb构造函数自定义属性
this.pro2=false;
}
//Subb继承Suaa
Subb.prototype=new Suaa();
//给Subb构造函数添加原型对象方法
Subb.prototype.get2=function(){
return this.pro2;
}
//创建Subb()的实例
var ins=new Subb();
//因为继承了Suaa所以拥有了Suaa的所有实例属性与方法,同时还有了指向Suaa原型对象的指针,所以也就有了Suaa的原型对象get1()方法
//其中搜索过程为先搜索实例,然后搜索Subb的原型,最后搜索所继承的Suaa原型
alert(ins.get1()); //true
组合继承
//组合继承
function Suaa(name){
this.name=name;
this.colors=["red","blue","green"];
}
Suaa.prototype.sayName=function(){
alert(this.name);
}
function Subb(name,age){
//继承了suaa的属性并传递了name参数
Suaa.call(this,name);
this.age=age;
}
//继承方法
Subb.prototype=new Suaa();
Subb.prototype.constructor=Subb;
Subb.prototype.sayAge=function(){
alert(this.age);
}
var ins1=new Subb("nike",29);
ins1.colors.push("black");
alert(ins1.colors);//red","blue","green,black
ins1.sayName();//nike
ins1.sayAge();//29
var ins2=new Subb("luce",25);
alert(ins2.colors);//red","blue","green
ins2.sayName();//luce
ins2.sayAge();//25
寄生组合式继承
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.call(this,name);
this.age=age;
}
inheritPrototype(SubType,SuperType);
SubType.prototype.sayAge=function(){
alert(this.age);
}
前端ABC