所有,我知道定義一個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
的好處,有什麼辦法可以做到嗎?或者我不知道的東西?謝謝。
你可能是指「mixin」,而不是「maxin」。 – georg 2013-04-08 10:19:44
對不起,錯字。修復它。謝謝。 – 2013-04-08 10:42:09
有關如何模擬受保護的類成員的想法,請參見以下問題:http://stackoverflow.com/questions/8703698/javascript-module-pattern-protected-members – 2013-04-08 11:11:19