DIV CSS 佈局教程網

JavaScript 原型繼承用法實例分析
編輯:關於JavaScript     

原型繼承是 JavaScript 面嚮對象的基礎。以 Person 與 Student 為例,可透過讓 Student 的原型指向 Person 的實例,實現方法共享與重寫。

示例代碼

function Person() {}
Person.prototype.walk = function() {
  alert('I am walking!');
};
function Student() {
  Person.call(this);
}
Student.prototype = new Person();
Student.prototype.constructor = Student;
Student.prototype.sayHello = function() {
  alert('hi, I am a student');
};
var student = new Student();
student.sayHello();
student.walk();

要點

Student.prototype = new Person() 後,需要手動修正 constructor 指向 Student。透過 instanceof 可判斷 student 是否同時屬於 Person 與 Student。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved