继承的定义:创建一个或多个类的专门版本类的方式称为继承。
javascript只支持单继承,创建的专门版本的类通常叫做子类,另外的类称为父类。在现代浏览器中你可以使用Object.create实现继承。
举个例子,定义一个父类Person类,然后定义Student类作为Person类的子类,之后重新定义sayHello()方法并添加了sayGoodbye()方法。
//定义Person构造器
function
Person(
firstName){
this.
firstName=
firstName;
}
//在Person.prototype中加入方法
Person.
prototype.
walk=
function(){
alert(
"I am walking!");
}
Person.
prototype.
sayHello=
function(){
alert(
"Hello, I'm "+
this.
firstName);
}
//定义Student构造器
function
Student(
firstName,
subject){
//调用父类构造器,确保“this”在调用过程中设置正确
Person.
call(
this,
firstName);
//初始化类Student类的特有属性
this.
subject=
subject;
}
//建立一个由Person.prototype继承而来的Student.prototype
//注意:常见的错误是使用“new Person()” 来建立Student.prototype
//这样做的错误之处有很多,最重要的一点是我们在实例化时
//不能赋予Person类任何的firstName参数
//调用Person的正确位置如下,我们从Student中来调用它
Student.
prototype=
Object.
create(
Person.
prototype);
//设置“constructor”属性指向Student
Student.
prototype.
constructor=
Student;
//更换SayHello方法
Student.
prototype.
sayHello=
function(){
console.
log(
"Hello,I'm "+
this.
firstName+
", I'm studying "+
this.
subject);
}
//加入sayGoodbye方法
Student.
prototype.
sayGoodBye=
function(){
console.
log(
"Goodbye!")
}
//测试实例
var
student1=
new
Student(
"John smith",
"chinese");
student1.
sayHello();
//Hello,I'm John smith, I'm studing chinese
student1.
walk();
//I am walking
student1.
sayGoodBye();
//Goodbye
//check that instanceof works correctly
console.
log(
student1
instanceof
Person);
// true
console.
log(
student1
instanceof
Student);
// true
运行结果: