javascript 對象繼承

繼承的定義:創建一個或多個類的專門版本類的方式稱爲繼承。

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

運行結果:





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章