首页 > 语言 > JavaScript > 正文

JavaScript高级程序设计 阅读笔记(十四) js继承机制的实现

2024-05-06 14:21:23
字体:
来源:转载
供稿:网友
继承

  继承是面向对象语言的必备特征,即一个类能够重用另一个类的方法和属性。在JavaScript中继承方式的实现方式主要有以下五种:对象冒充、call()、apply()、原型链、混合方式。

  下面分别介绍。

对象冒充

  原理:构造函数使用this关键字给所有属性和方法赋值。因为构造函数只是一个函数,所以可以使ClassA的构造函数成为ClassB的方法,然后调用它。ClassB就会收到ClassA的构造函数中定义的属性和方法。

  示例:
代码如下:
function ClassA(sColor){
this.color=sColor;
this.sayColor=function(){
alert(this.color);
}
}

function ClassB(sColor,sName){
this.newMethod=ClassA;
this.newMethod(sColor);
delete this.newMethod;

this.name=sName;
this.sayName=function(){
alert(this.name);
}
}

调用:
代码如下:
var objb=new ClassB("blue","Test");
objb.sayColor();//
blueobjb.sayName(); // Test  


注意:这里要删除对ClassA的引用,否则在后面定义新的方法和属性会覆盖超类的相关属性和方法。用这种方式可以实现多重继承。

call()方法

  由于对象冒充方法的流行,在ECMAScript的第三版对Function对象加入了两个新方法 call()和apply()方法来实现相似功能。

  call()方法的第一个参数用作this的对象,其他参数都直接传递给函数自身。示例:
代码如下:
function sayColor(sPrefix,sSuffix){
alert(sPrefix+this.color+sSuffix);
}

var obj=new Object();
obj.color="red";

//output The color is red, a very nice color indeed.
sayColor.call(obj,"The color is ",", a very nice color indeed.");

 使用此方法来实现继承,只需要将前三行的赋值、调用、删除代码替换即可:
代码如下:
function ClassB(sColor,sName){
//this.newMethod=ClassA;
//this.newMethod(sColor);
//delete this.newMethod;
ClassA.call(this,sColor);

this.name=sName;
this.sayName=function(){
alert(this.name);
}
}


apply()方法

  apply()方法跟call()方法类似,不同的是第二个参数,在apply()方法中传递的是一个数组。
代码如下:
function sayColor(sPrefix,sSuffix){
alert(sPrefix+this.color+sSuffix);
}

var obj=new Object();
obj.color="red";

//output The color is red, a very nice color indeed.
sayColor.apply(obj,new Array("The color is ",", a very nice color indeed."));

使用此方法来实现继承,只需要将前三行的赋值、调用、删除代码替换即可:
代码如下:
function ClassB(sColor,sName){
//this.newMethod=ClassA;
//this.newMethod(sColor);
//delete this.newMethod;
ClassA.apply(this,new Array(sColor));

this.name=sName;
this.sayName=function(){
alert(this.name);
}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选