JavaScript中的继承(一)

    在javascript中不存在面向对象中的继承关系,我们可以通过很多种手段来实现继承机制,先看一个简单的例子:

//基类Person
function Person(name,age){
  
this.name=name;
  
this.age=age;
  
this.shout=function(){
    alert(
"I'm a person.");
  }

}


//Person子类Teacher
function Teacher(name,age){
  
this.temp=Person;
  
this.temp(name,age);
  
delete temp;
}
    我们先定义了一个Person类(我习惯站在面向对象的角度来称呼它,当然,你可以称它为函数),含有两个属性name,age和一个方法shout,让Teacher类继承Person类的办法是为Teacher添加一个临时函数temp,先让temp指向Person这个构造函数,然后调用temp(name,age)时实际则是调用了Person(name,age)这个构造函数,这样就Teacher就继承了Person的所有属性和方法,最后只需删除temp这个临时函数即可。当然,如果你需要为Teacher添加新的方法或是重写Person的方法时,你可以在delete temp之后添加。


    上面的例子也可以用call函数或apply函数实现,这样用起来更加简单:
//基类Person
function Person(name,age){
  
this.name=name;
  
this.age=age;
  
this.shout=function(){
    alert(
"I'm a person.");
  }

}


//Person子类Teacher
function Teacher(name,age){
  
//this.temp=Person;
  //this.temp(name,age);
  //delete temp;
  Person.call(this,name,age);
}
用apply实现只需将Teacher中Person.call(this,name,age);换为Person.apply(this,[name,age]);

posted on 2008-02-16 01:22 welkin 阅读(142) 评论(0)  编辑  收藏 所属分类: JavaScript


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


网站导航:
 
<2025年7月>
293012345
6789101112
13141516171819
20212223242526
272829303112
3456789

导航

统计

公告

 

留言簿

文章分类(3)

文章档案(3)

搜索

最新评论