在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]);