继承,通俗地说,之前你写过一些类,这些类中有一些是而你现在要写的类的功能的子集或者基本相同,那么你不用完全重新写一个新的类,你可以把之前写的类拿过来使用.这样的一种代码重用过程就叫做继承. 深入学习javascript继承之前,先了解下面的几个概念: 父类:被继承的类 子类:由继承得来的类 超类:也就是父类 抽象类:一般不用来实例化的类,它的用途是用来给其他类继承. 基类:提供给其他类可以继承的类 派生类:由基类继承而来的类
javascript对象继承通常有下面的5种方式: 1.对象冒充 2.call()方式 3.apply()方式 4.原型链 5.混合方式 A.对象冒充 所谓对象冒充,就是新的类冒充旧的类(旧的类必须采用构造函数方式),从而达到继承目的. eg.1 function people(name,sex,age){ //使用构造函数方式 this.name=name; this.sex=sex; this.age=age; this.say=function(){ alert("My name is "+this.name); }; this.doing=function(){ alert("I am speaking"); }; } var Marry=new people("Marry","Woman","23"); Marry.say(); Marry.doing(); function white_people(name,sex,age){ this.inherit=people; this.inherit(name,sex,age); delete this.inherit; this.area=function(){ alert("I am in Europe"); } } var Tom=new white_people("Tom","man","21"); Tom.say(); Tom.area(); alert(Tom.age);
上面的例子中,people是用来做white_people的基类,记住这个格式是用来对象冒充达到继承目的的
this.inherit=people; //冒充 this.inherit(name,sex,age); //继承 delete this.inherit; //删除继承
所有新属性和新方法都必须再删除了继承后定义,这样是为了避免覆盖父类的相关属性和方法. 另外,对象冒充支持多继承. eg.2 function worker(pay,work){ this.pay=pay; this.work=work; } function city_worker(name,sex,age,pay,work){ this.inherit=people; this.inherit(name,sex,age); delete this.inherit; this.inherit=worker; this.inherit(pay,work); delete this.inherit; } var Jerry=new city_worker("Jerry","man","21","$1000","coder"); Jerry.say(); alert(Jerry.work);
对象冒充有一个不足的地方:多继承机制实现时,如果基类存在相同的属性或者方法,将从后面的类继承. B.call()方式 只是封装的对象冒充的一个函数.这样,我们不再需要写"经典"的三句话,而是用下面这句话代替: 基类.call(对象,参数列表) eg.1
function farmer(name,sex,age,pay,work){ people.call(this,name,sex,age); worker.call(this,pay,work); } var Nicholas=new farmer("Nicholas","man","27","$3000","irrigator"); Nicholas.say(); alert(Nicholas.pay);
飞飞Asp技术乐@园 同样,call()存在同名属性和方法的小问题. C.apply()方式 和call()一样.apply()也是对象冒充的一个封装函数.其格式为: 基类.apply(对象,参数数组); eg.1
function white_collar(name,sex,age,pay,work){ people.apply(this,new Array(name,sex,age)); worker.apply(this,[pay,work]); } var Jiessie=new white_collar("Jiessie","woman","26","$2500","editor"); Jiessie.say(); alert(Jiessie.work);
同样,apply()存在同名属性和方法的小问题. D.原型链 上面三种方式都是采用构造函数方式的继承,对应地,也具有原型函数方式的继承:原型链. eg.1 function blue_collar(){ } blue_collar.prototype.name="Jean"; blue_collar.prototype.age="33"; blue_collar.prototype.say=function(){ alert("my name is "+ this.name); }; function city_blue_collar(){ } city_blue_collar.prototype=new blue_collar(); var jj=new city_blue_collar; jj.say();
原型链也具有了原型链的缺点:不能传递参数.另外,原型链不支持多继承,因为 E.混合方式 使用构造函数方式来写类的属性,对属性的继承采用call()或者apply() 使用原型方式来写的方法,对方法的继承采用原型链 eg.1 function beauty(name,age){ this.name=name; this.age=age; } beauty.prototype.say=function(){ alert("小女叫"+this.name); }; function china_beauty(name,age,area){ beauty.call(this,name,age); this.area=area; } china_beauty.prototype=new beauty(); china_beauty.prototype.from=function(){ alert("我来自"+this.area); }; var diaochan=new china_beauty("貂禅","16","临洮"); diaochan.say(); diaochan.from(); alert(diaochan.age);
|