2010-08-19 73 views
3

我知道'this'在封閉內外有所不同。
但爲什麼numChildren和this.numChildren在閉包內部有所不同?
或者爲什麼numChildren在外部和內部是相同的?關閉內的'this'關鍵字

var _this:Sprite = this; 
trace("[outside]this: " + this); 
trace("[outside]numChildren: " + numChildren); 
trace("[outside]this.numChildren: " + this.numChildren); 

(function():void { 
    trace("[inside]this: " + this); 
    trace("[inside]numChildren: " + numChildren); 
    trace("[inside]this.numChildren: " + this.numChildren); 
    trace(_this.removeChildAt === removeChildAt); 
    trace(this.removeChildAt === removeChildAt); 
})(); 

你可以看到代碼和輸出從以下鏈接
How Do You Explain 'this'?

回答

4

你不能用關鍵字「這」從內部封閉訪問類。這就是爲什麼你會得到跟蹤結果。 在您的示例中,訪問該類的唯一方法是使用_this變量。在閉包內部,「this」是指全局對象,你不在該類的範圍內。

numChildren在外部和內部是相同的,因爲它是類的屬性,與如果在閉包內跟蹤&之外的「name」屬性的方式相同,您將得到完全相同的結果。換句話說,不能通過使用「this」來訪問類,並不意味着你不能訪問它的屬性。

當你寫this.name或this.numChildren,瓶蓋內,你不是指類的了,因此,不同的跟蹤輸出

+0

感謝您的詳細解釋! – 9re 2010-08-19 13:08:03