继承是面向对象的重要特征之一。在万事万物皆对象的面向对象语言中 中子类继承并实现父类的一些属性和方法.,从而实现代码的复用,利于软件的开放性和扩充性,同时减少了一些不必要的类的出现。
具体应用如下:
Javascript本身也是一种基于对象的语言,但是对继承提供的语法上的支持不完善,可以用对象冒充实现相关机制。
对象冒充是指一个对象冒充另外一个对象来还行其他对象的方法,即一个对象将其他对象的方法当做是自身的方法来执行。JS中的call和apply两个方法可以实现这种机制,两者格式略有不同。
FunctionName.Call(object.,argument1,argument2,argument3…)
FunctionName.apply(object,[argument1,argument2,argument3…])
具体应用如下:
Function Student(studyNo)
{
This. studyNo = studyNo;
}
People.prototype.getNO=function()
{
Return this.studyNo;
}
Var studentA = new student(“studentA 001”)
Var studentB = new student(“studentB 002”)
alert(studentA. getNO);
alert(studentB. getNO.);
alert(studentA. getNO.call(studentB));
alert(studentA. getNO.apply(studentB,[]))
getNO函数调用了call和apply方法,所以getNO函数被当做两个方法的第一个参数studentB所指定的对象的方法来执行。Call的实参以参数的形式出现,apply的形参被放入数组中。
具体实例:
function student(name)
{
Var name =name;
This.getName=function()
{
return name;
}
}
function studentA(name ,studyNo)
{
Student.call(this,,”studentA”);
this.name=name;
this.studyNo=studyNo;
}
Var studentA =new StudentA(甲);
Var name=studentA.getName();
Alert(name);
上述代码的关键在于Student.call(this,studentA);采用了对象冒充机制调用了父类的构造函数,是的子类studentA中也有了student类在其构造函数中所定义的内容,达到了继承的效果。