ActionScript3のthis について。

ActionScript3のthis について少し迷った。これまでは、なんとなく以下のように感じながら、明確な理解をせずになんとかなっていた。

    • JavaScriptのthisとは違うなぁ。ちゃんとオブジェクト見続けている感じ。
    • その意味でJavaのthisとだいたい似てるけど、でも無名関数の中で使うときだけJavaScriptっぽい動きをするなぁ。

今回、ちょっと複雑なコードを書くようになり、ちゃんと理解しないといけない羽目になった。


http://livedocs.adobe.com/flex/3/html/help.html?content=03_Language_and_Syntax_21.html

The value of the this reference within the body of an instance method is a reference to the instance to which the method is attached.

A bound method, sometimes called a method closure, is simply a method that is extracted from its instance. Examples of bound methods include methods that are passed as arguments to a function or returned as values from a function. New in ActionScript 3.0, a bound method is similar to a function closure in that it retains its lexical environment even when extracted from its instance. The key difference, however, between a bound method and a function closure is that the this reference for a bound method remains linked, or bound, to the instance that implements the method. In other words, the this reference in a bound method always points to the original object that implemented the method. For function closures, the this reference is generic, which means that it points to whatever object the function is associated with at the time it is invoked.

    • クラス定義の中でメソッドとして書いた関数を取り出すと、Bound Methodとなって関数クロージャと同様にもとのインスタンスの環境を引き継ぐ。
    • 関数クロージャでは、thisキーワードが指すものは関数が実行されるcontextによって変化するが、
    • Bound Methodでは、thisキーワードが指すものは、メソッドが属するインスタンスであり続ける。

とのこと。すなわち:

    • メソッドの中のthisと非メソッド関数の中のthisは結構違う。
    • メソッドの中のthisはインスタンスを指し続けるが、
    • 非メソッド関数の中のthisはJavaScript的に何を指すかが走行環境によって決まる。

ということらしい。なるほどねぇーー^^ 最初に書いた「いい加減な理解」もまんざら間違ってなかったということか。