Flyingis

Talking and thinking freely !
Flying in the world of GIS !
随笔 - 156, 文章 - 16, 评论 - 589, 引用 - 0
数据加载中……

JavaScript 中的继承(上)

    作者:Flyingis

    继承是面向对象语言基本特征之一,通过继承可以将父类所具有的特性遗传到子类。ECMAScript中的继承不像Java、C++等语言那么明显,直接通过关键字来实现,通常它是通过模拟方式来实现继承功能的,并且实现方式有多种。

    在继承中引入this关键字,使用构造器方法定义类来实现继承。一个构造器是一个函数,因此可以将父类的构造器作为子类的一个方法使用并进行调用。

function ClassA(id) {
  
this .id = id;
  
this .sayId = function() {
     alert(
this.id);
   }
;
}


function ClassB(id, name) {
  
this .newMethod = ClassA;
  
this .newMethod(id);
  
delete this.newMethod;

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

    注意,子类中所有新的属性和方法都必需在删除newMethod后引入,否则,可能存在用父类的属性和方法重写子类属性和方法的危险。另外,使用这种方法还可以实现多重继承,此时如果两个父类具有相同的属性或方法时,最后的类具有优先级。由于这种继承方法比较流行,ECMAScript第三版引入了两个Function对象:call()和apply()。

    call()

    call()方法是最接近上述继承方式的方法,它的第一个参数是this指向的对象,所有的其他参数都直接传到function。

function sayMessage(first, last) {
   alert(first
+ this.logic +last);
}
;

varobj =new Object();
obj.logic
= "or";

sayMessage.call(obj,
"Coffee ""Tea");  //输出"Coffee or Tea"

    用call()方法来实现继承,只需要this.newMethod相关的三行代码。

function ClassB(id, name) {
  
  //this.newMethod = ClassA;
  //this.newMethod(id);
  //delete this.newMethod;
  ClassA.call(this, id);  //this指向ClassB的对象

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

    apply()

    apply()方法需要两个参数:this所指向的对象,和传到function的由参数组成的array。

function sayMessage(first, last)  {
  alert(first 
+ this.logic +last);
}
;

var obj = new Object();
obj.logic 
= "or";

sayMessage.apply(obj, 
new Array("Coffee "" Tea"));  //输出"Coffee or Tea"
  
    同样,使用 apply() 实现继承可以通过如下方法实现。

function ClassB(id, name) {
  
//this.newMethod = ClassA;
  //this.newMethod(id);
  //delete this.newMethod;
  ClassA.apply(thisnew Array(id));  //this指向ClassB的对象

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

    当父类构造器的参数和子类构造器参数的顺序一致时,可以使用子类的arguments对象作为第二个参数。否则,必需创建一个array来传递参数,或是使用call()方法。

    文章待续……

posted on 2006-07-15 10:38 Flyingis 阅读(1591) 评论(0)  编辑  收藏 所属分类: Web 客户端技术


只有注册用户登录后才能发表评论。


网站导航: