2012-08-25 28 views
0

我有一個如此基本的JavaScript問題,我甚至不能製作一個適當的谷歌查詢來回答它。舉例來說:如何引用原型的父項?

function Parent(name){ 
    this.name = name; 
} 

Parent.prototype.Child() = function(){ 
    if(this.name == 'Sam'){ // This is the comparison that obviously doesn't work 
    /* Do something */ 
    } else { 
    /* Do something else */ 
    } 
} 

var Parent1 = new Parent('Sam'); 
var Child1 = new Parent1.Child(); 

是否有一個關鍵字可以在比較中用來代替這個來訪問Parent的「name」屬性?

乾杯!

+0

'Parent.prototype.Child()= function(){'應該是'Parent.prototype.Child = function(){' – Musa

回答

1

這個例子不起作用,因爲你有它不屬於的()。它應該是這樣的:

Parent.prototype.Child = ... 

而且,在這條線..

var Child1 = new Parent1.Child(); 

...應該是

var Child1 = Parent1.Child(); 

我們拿出new因爲Parent1不是構造函數。

您的代碼將按照您的預期行事。

1
var Parent1= new Parent('sam') 

因爲parent1必須使用兒童功能

的能力,這將創建一個名爲parent1

一個對象,它應該是

Parent.prototype.Child = function(){ 

最後你可以使用這個

parent1.child()