2013-01-02 137 views
1

我試圖在Javascript中更好地理解OOP。有人可以解釋下面的例子中如何使用create方法和替代方法嗎?我在網上查了一下,查看了幾篇關於SO的文章,但仍然沒有掌握下面代碼中發生的事情。我提供了評論來說明我的理解。請糾正我錯在哪裏。瞭解Javascript構造函數:自定義創建方法

這個例子是用來覆蓋從基類的方法:

// Defines an Employee Class 
function Employee() {} 

// Adds a PayEmployee method to Employee 
Employee.prototype.PayEmployee = function() { 
    alert('Hi there!'); 
} 

// Defines a Consultant Class and 
// Invokes the Employee Class and assigns Consultant to 'this' -- not sure and not sure why 
// I believe this is a way to inherit from Employee? 
function Consultant() { 
    Employee.call(this); 
} 

// Assigns the Consultant Class its own Constructor for future use -- not sure 
Consultant.prototype.constructor = Consultant.create; 

// Overrides the PayEmployee method for future use of Consultant Class 
Consultant.prototype.PayEmployee = function() { 
    alert('Pay Consultant'); 
} 
+2

老闆,哪裏還有我的薪水是多少? 〜''你好!':'P' –

+4

'Object.create'在該代碼中根本沒有被使用。 –

+0

和'Consultant.create'不存在。 @ T.J .:你解釋了這一千次,你肯定找到最好的重複;) –

回答

4

此代碼:

function Consultant() { 
    Employee.call(this); 
} 

正在調用的Employee構造顧問構造函數被調用時(即,當一個顧問實例創建)。如果Employee構造函數正在進行任何初始化,那麼在創建Consultant「子類型」時調用它會很重要。

此代碼:

Consultant.prototype.constructor = Consultant.create; 

有點的謎。這意味着有一個名爲create的函數,它是Consultant函數對象的一個​​屬性。但是,在您發佈的代碼示例中,沒有此類屬性。實際上,這條線將undefined分配給顧問構造函數。

你的問題不問,只是僅供參考,我認爲你可能想這條線的代替與創造功能,是這樣的:

Consultant.prototype = new Employee(); 
Consultant.prototype.constructor = Consultant; 

這就是原型繼承模式。這當然不是唯一或必然的最佳方法,但我喜歡它。

更新

如果員工需要一個參數,你可以處理像這樣:

// Employee constructor 
function Employee(name) { 
    // Note, name might be undefined. Don't assume otherwise. 
    this.name = name; 
} 

// Consultant constructor 
function Consultant(name) { 
    Employee.call(this, name); 
} 

// Consultant inherits all of the Employee object's methods. 
Consultant.prototype = new Employee(); 
Consultant.prototype.constructor = Consultant; 
+3

請不要'Consultant.prototype = new Employee();'。只要'員工'不期待任何爭論,這就行得通了。但如果它呢?在這個階段,你並不是真的想要調用構造函數(稍後在子構造函數中這樣做),你只是想將原型放入鏈中。這可以通過'Object.create'輕鬆完成:'Consultant.prototype = Object.create(Employee.prototype)'。 –

+0

'Consultant.prototype = new Employee();'是原型繼承模式的重要組成部分。它確保了每當你做新的Consultant()(有或沒有參數)時,新的Consultant對象將擁有Employee對象在新'Employee()'時所擁有的所有方法。請注意,使用此模式的一個缺點是,如果「基本」構造函數Employee帶有參數,則它必須能夠在沒有參數傳遞時處理該情況。 – dgvid

+1

也許我沒有明確表達自己:爲了避免這個缺點,你應該使用Object.create代替。爲了確保一個新的Consultant對象被正確初始化,你可以在Consultant構造函數中調用Employee的構造函數。就這樣。正如我所說的,在那個時候,你不想創建一個'Employee'實例,你只是想把它的原型放到原型鏈中。 'Object.create'可以讓你在不初始化一個新的'Employee'對象的情況下做到這一點。 –

相關問題