我正在閱讀從Mozilla開發者網絡獲得的Introduction to Object-Oriented JavaScript,在開始使用node.js之前學習如此嚴肅的Javascript。有一些關於Javascript繼承的東西,我不明白
無論如何,繼承的東西似乎對我來說太晦澀了。從文檔複製並粘貼:
// define the Person Class
function Person() {}
Person.prototype.walk = function(){
alert ('I am walking!');
};
Person.prototype.sayHello = function(){
alert ('hello');
};
這是很容易的,但事情變得複雜與Student
繼承。還有人認爲以下三種說法基本上是一樣的嗎?
// define the Student class
function Student() {
// Call the parent constructor
Person.call(this);
}
// inherit Person
Student.prototype = new Person();
// correct the constructor pointer because it points to Person
Student.prototype.constructor = Student;
我瞭解第一個(調用父構造函數),因爲它與Java,PHP等非常相似。但隨後問題就開始了。
爲什麼需要致電Student.prototype
和?Student.prototype.constructor
需要明確的解釋。爲什麼這個代碼:
// define the Student class
function Student() {
// Call the parent constructor
Person.call(this);
}
var student1 = new Student();
是不夠的繼承工作?
編輯:關於構造函數,已經回答了here。
的[?爲什麼要設置原型構造]可能重複(http://stackoverflow.com/questions/8453887/why -s-it-it-it-set-the-prototype-constructor) – pimvdb
「面向對象的JavaScript」不存在,Javascript是面向原型的,你必須使你的面向對象的方法適應原型。 – Chiguireitor
@Chiguireitor我沒有寫文檔標題,你知道... – gremo