我對JS中的OOP是一種新的東西。我想知道爲什麼當創建子對象時,這會停止在第二級子對象之後引用主對象。「這個」不是指當前對象
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();
所以,據我所知之後的某一點,「這個」停止指的類「CLASE」,指的是什麼其他。如果是這樣,以這種方式使用閉包是一種很好的做法嗎?
以self = this開始課程也是正確的;從那時起只使用「自我」?例如:http://jsfiddle.net/byGRX/
「這」可以改變在一個類似的問題被問到[這裏](http://stackoverflow.com/questions/3127429/javascript-this-keyword),第一個反應鏈接到一個關於這個問題的好文章。 – Bubbles
謝謝,這個鏈接很有趣,但它不能回答我的問題。我仍然不知道爲什麼當我在對象層下去時這個'丟失'。 – bgusach