舉個例子,定義一個父類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