原型繼承是 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。