4

我正在閱讀從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.prototypeStudent.prototype.constructor

需要明確的解釋。爲什麼這個代碼:

// define the Student class 
function Student() { 
    // Call the parent constructor 
    Person.call(this); 
} 

var student1 = new Student(); 

是不夠的繼承工作?

編輯:關於構造函數,已經回答了here

+3

的[?爲什麼要設置原型構造]可能重複(http://stackoverflow.com/questions/8453887/why -s-it-it-it-set-the-prototype-constructor) – pimvdb

+0

「面向對象的JavaScript」不存在,Javascript是面向原型的,你必須使你的面向對象的方法適應原型。 – Chiguireitor

+1

@Chiguireitor我沒有寫文檔標題,你知道... – gremo

回答

2

這不起作用:

function Student() { 
    Person.call(this); 
} 

var student1 = new Student(); 

因爲Person的原型屬性不可用在Student實例。 Person.call(this)僅僅調用Person與特定的this值(即Student實例)。但Person功能是完全空的 - 所以在這裏它什麼都不做。 StudentPerson之間沒有任何關係,除了無用的Person調用。

要獲得Person的功能.prototype指派是必要的。

前:

<a Student instance> 
    its prototype: Student.prototype, with all student functions 
    its prototype: Object.prototype 

後:

<a Student instance> 
    its prototype: <a Person instance>, with all student functions if you add them 
    its prototype: Person.prototype, with all person functions 
     its prototype: Object.prototype