为了节省时间,就不打算写太多文字说明了,直接代码才是王道:
1,原型链式继承
function SuperType(){
this.property=true;
}
SuperType.prototype.getSuperValue=function(){
return this.property;
}
function SubType(){
this.property=false;
}
SubType.prototype=new SuperType(); //继承了SuperType
SubType.prototype.getSubValue=function(){
return this.property;
}
var instance=new SubType();
alert(instance.getSuperValue); //true 这就是继承体现出来的,实例木有此方法所有搜索原型,原型指向SuperType(即SuperType是它的原型,有此方法)
alert(instance instanceof Object); //true
alert(instance instanceof SuperType); //true
alert(instance instanceof SubType); //true 凡在原型链中出现都构造函数用instanceof 操作符都会返回true
alert(Object.prototype.isPrototypeOf(instance)); //true
alert(SuperType.prototype.isPrototypeOf(instance)); //true
alert(SubType.prototype.isPrototypeOf(instance)); //true
有两点需要注意的:
(1)给原型添加方法的代码一定要放在替换原型的语句之后
(2)通过原型链实现继承时,不能使用对象字面量创建原型方法,因为这样做会重写原型链
原型链存在的问题:
就是前面那篇创建对象中谈到的引用类型属性会被所有实例共享的问题,此外还有一个问题就是不能向超类型的构造函数传递参数,因此实践中很少单独使用原型链。
2,借用构造函数:
function SuperType(name){
this.name=name;
this.colors=["red","blue","green"];
}
function SubType(){
SuperType.call(this); //继承了SuperType,为什么会继承呢?不懂的童鞋认真回去复习call函数
}
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" 这里就不会出现共享问题了,因为每个实例都有自己的colors属性副本
也可以传递参数了:
function SubType(){
SuperType.call(this,"rason2008");
this.age=20;
}
var instance =new SubType();
alert(instance.name); //"rason2008"
alert(instance.age); //20
借用构造函数存在的问题:函数复用无从谈起
3,最常用的继承模式:组合继承
function SuperType(name){
this.name=name;
this.colors=["red","blue","green"];
}
SuperType.prototype.sayName(){
alert(this.name);
}
function SubType(name,age){
SuperType.call(this,name); //继承属性
this.age=age;
}
SubType.prototype=new SuperType(); //继承方法
SubType.prototype.sayAge=function(){
alert(this.age);
}
var instance1=new SubType("rason2008",20);
instance1.colors.push("black");
alert(instance1.colors); //"red,blue,green,black"
instance1.sayName(); //"rason2008"
instance1.sayAge(); //20
var instance2=new SubType("lily",20);
alert(instance2.colors); //"red,blue,green"
instance2.sayName(); //"lily"
instance2.sayAge(); //20