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

继承

  继承是面向对象语言的必备特征,即一个类能够重用另一个类的方法和属性。在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();// blue
objb.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);
}
}

  跟call()有一点不同的是,如果超类中的参数顺序与子类中的参数顺序完全一致,第二个参数可以用arguments。

原型链

  继承这种形式在ECMAScript中原本是用于原型链的。Prototype对象的任何属性和方法都被传递给那个类的所有实例。原型链利用这种功能实现继承机制。

  用原型链实现继承示例:

function ClassA(){
}

ClassA.prototype.color="red";
ClassA.prototype.sayColor=function(){
alert(this.color);
};

function ClassB(){
}

ClassB.prototype=new ClassA();

  注意:调用ClassA的构造函数时,没有给它传递参数。这在原型链中是标准的做法,要确保构造函数没有任何参数。

混合方式

  这种方式混合了对象冒充和原型链方式。示例:

function ClassA(sColor){
this.color=sColor;
}
ClassA.prototype.sayColor=function(){
alert(this.color);
}

function ClassB(sColor,sName){
ClassA.call(this,sColor);
this.name=sName;
}

ClassB.prototype=new ClassA();
ClassB.prototype.sayName=function(){
alert(this.name);
}

  调用示例:

var objb=new ClassB("red","test");
objb.sayColor();// output red
objb.sayName();// output test
posted @ 2012-04-01 14:37  artwl  阅读(698)  评论(0编辑  收藏  举报

个人简介

var ME = {
	"name": "土豆/Artwl",
	"job": "coding",
	"languages": [
		"JS", "HTML",
                "CSS", "jQuery"
		"MVC",".NET",
		"设计模式"
	],
	"hobby": [
		"阅读", "旅游",
		"音乐", "电影"
	]
}
TOP