2012-05-28 219 views
0

我的情況下,(爲什麼 「測試1」 沒有出現在警報窗口):爲什麼JavaScript原型不工作在這種情況下

var Parent=function(){ 
    this.test1= function(){ 
     alert("test1"); 
    } 
} 

var Child=function(){ 
    this.prototype=new Parent(); 
} 

var test=new Child(); 
test.test1(); 

http://jsfiddle.net/c3sUM/2/(相同的代碼在網上試試)

感謝

+0

請使用函數聲明而不是函數表達式。這裏使用表達式沒有任何好處。 – RobG

回答

4

問題是您沒有分配Child的原型,而是在Child的實例中創建了一個屬性prototype,該實例指向Parent的實例。

instead, do this

var Child = function(){};  // create constructor 
Child.prototype = new Parent(); // assign instance of parent to constructor's 
           // prototype 

A similar answer可能有助於

+0

http://jsfiddle.net/c3sUM/3/ - 謝謝,但你的解決方案不起作用 – Yosef

+0

@Yosef對不起,我不清楚。我用演示更新了答案。 – Joseph

+0

謝謝!是否存在從Child類內部繼承的方法? – Yosef

0

您的代碼將更加清晰使用函數聲明:

// Parent constructor 
function Parent() {} 

// Methods of Parent.prototype are inherited by 
// instances of parent 
Parent.prototype.test1 = function() { 
    alert('test 1'); 
} 

// Child constructor 
function Child(){} 

// Make Child.prototype an instance of Parent so 
// instances inherit from Child and Parent 
Child.prototype = new Parent(); 

// Instance inherits from Child (and hence Parent); 
var child = new Child(); 

child.test1(); // 'test 1' 

在這種情況下使用了聲明函數表達式的唯一原因是如果你想動態創建基於其他邏輯的構造函數。

相關問題