2013-04-08 34 views
2

所有,我知道定義一個JavaScript OOP對象的傳統方式。這裏是例子。Mixin遺傳模式的javascript丟失Closure功能

var TField=function(jData) 
{ 
    this.id=jData.id; 
    this.name=jData.name; 
    this.attributes=jData.attributes; 
    TField.prototype.render=function(){ 
     alert(jData.id); 
    }; 
}; 

我們可以發現TField.prototype.render知道什麼是jData的值時,它被稱爲,這是因爲Closure的功能。

但現在我只是試圖在JavaScript中實現繼承。我發現推薦的方法是Mixin pattern。 這是我迄今爲止所做的代碼。

TChildField.prototype.render=function(){ 
     alert('TChildField render.'); 
     //Can not utilize the parameters of the constructor. like jData 
}; 


var TField=function(jData) 
{ 
    this.id=jData.id; 
    this.name=jData.name; 
    this.attributes=jData.attributes; 

}; 

TField.prototype.render=function(){ 
     alert('TField render.'); 
}; 

var TChildField=function(jData) 
{ 
    TField.call(this,jData) 
} 

var tobj={id:"1",name:"test",attribute:{}}; 
TChildField.prototype=Object.create(TField.prototype) 
TChildField.prototype.render=function(){ 
     alert('TChildField render.'); 
}; 
var c= new TChildField(tobj); 
alert(c.id); 
alert(c.name); 

好吧,它工作正常,沒有問題。但我的問題是我發現我不能像使用TField一樣使用TChildField構造函數的參數jData。我知道我可以定義this.Data=jData,以便我可以在TChildField.prototype.render中使用它,但我不希望它作爲屬性。最糟糕的是它失去了Closure的好處,有什麼辦法可以做到嗎?或者我不知道的東西?謝謝。

+0

你可能是指「mixin」,而不是「maxin」。 – georg 2013-04-08 10:19:44

+0

對不起,錯字。修復它。謝謝。 – 2013-04-08 10:42:09

+0

有關如何模擬受保護的類成員的想法,請參見以下問題:http://stackoverflow.com/questions/8703698/javascript-module-pattern-protected-members – 2013-04-08 11:11:19

回答

1

你需要什麼封裝?設置this.Data=jData有什麼不對?這很簡單,它可以解決您的問題。爲什麼最糟糕的是失去了關閉的好處?實際上應該避免封閉,因爲它們可能導致非常時髦的問題(內存泄漏?)。

+0

我認爲這就是問題的關鍵:你怎麼能使'jData'只對類的方法可用。 – 2013-04-08 11:09:37

+0

@ IgorZinov'yev你不能在外面看到它。 – freakish 2013-04-08 11:10:05