在上面的文章中我们讲了原型继承,借用构造函数继承,混合继承,它们各自有自己的优缺点。下面我们自己来模仿一些一些框架的继承
//混合继承的 ,继承了父类两次模板,一次原型对象,
//如果父类中有几百个属性。那么这种继承就不是很效率
function inherit(ChildClass, SuperClass){
//创建一个空函数,可以用来做装转
var F =new Function();
//实现空函数的原型对象和超类的原型对象进行转换
F.prototype = SuperClass.prototype;
//接着实现原型继承
ChildClass.prototype = new F();
//还原子类构造器
ChildClass.prototype.constructor = ChildClass;
//保存父类原型对象,方便解耦,方便获得父类原型对象
ChildClass.Childsuperclass = SuperClass.prototype;
//判断父类原型对象的构造器
if(SuperClass.prototype.constructor == Object.prototype.constructor){
SuperClass.prototype.constructor = SuperClass;
}
}
/*父类*/
function Father(name ,age){
this.name = name ;
this.age = age ;
}
/*父类原型对象*/
Father.prototype = {
constructor:Father,
say: function(){
alert('js')
}
}
/*子类*/
function Son(name,age,job){
//Father.call(this,name,age)//复制了一次模板
Son.Childsuperclass.constructor.call(this,name,age)//看出解耦,不直接用Father.call或者Father.apply
this.job = job;
}
//Son.prototype = new Father(); //再次复制了一次模板.这种方式来继承还是有缺点,他又继承了父类的模板
inherit(Son,Father);
var lzr = new Son('1111',22,'工作');
alert(lzr.name)
alert(lzr.age)
alert(lzr.job)
lzr.say();