您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

JavaScript 继承使用分析_js面向对象

2024/3/21 1:56:07发布43次查看
深入学习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);
同样,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);
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product