私はJSのOOPに少し慣れていません。サブオブジェクトを作成するときに、サブオブジェクトの2番目のレベルの後でメインオブジェクトの参照を停止する理由を知りたいです。
function Clase()
{
this.__construct = function()
{
this.paginator();
alert('__construct finished');
};
this.paginator = function()
{
this.paginator.title = function()
{
this.paginator.title.set_offsets = function()
{
alert('paginator.title.set_offsets executed!');
};
};
this.paginator.title(); //instantiating
alert('subobject paginator created');
};
this.__construct();
}
var instancia = new Clase();
instancia.paginator.title.set_offsets();
エラーは次のとおりです。this.paginatorが未定義です。
そして今、私がクロージャを使用する場合、それは完全に機能します:
function Clase()
{
self = this;
this.__construct = function()
{
this.paginator();
alert('__construct finished');
};
this.paginator = function()
{
self.paginator.title = function()
{
self.paginator.title.set_offsets = function()
{
alert('instancia.paginator.title.set_offsets() executed');
};
};
self.paginator.title();
alert('this.paginator created');
};
this.__construct();
}
var instancia = new Clase();
instancia.paginator.title.set_offsets();
したがって、ある時点でAFAIKは、「this」はクラス「Clase」の参照を停止し、他の何かを参照します。もしそうなら、このようにクロージャを使用するのは良い習慣ですか?
self=thisでクラスを開始することも正しいですか。それ以降は「自己」のみを使用しますか?例: http: //jsfiddle.net/byGRX/