Scope Of The This Keyword - MACROMEDIA FLASH MX 2004-USING ACTIONSCRIPT IN FLASH Use Manual

Using actionscript in flash
Hide thumbs Also See for FLASH MX 2004-USING ACTIONSCRIPT IN FLASH:
Table of Contents

Advertisement

This code cannot work correctly because there is a problem involving scope with the event
handlers, and what
The behavior that you might expect in this example is that the
be invoked in the scope of the Loader object; but it is invoked in the scope of the LoadVars object
because the method has been extracted from the Loader object and grafted onto the LoadVars
object. The LoadVars object then invokes the
successfully loaded, and the
not Loader. The
onLoadVarsDone()
expecting a
params_lv.params_lv
To correctly invoke the
use the following strategy: Use a function literal to create an anonymous function that calls the
desired function. The
can be used to find the calling Loader object.
class Loader {
var params_lv:LoadVars;
function Loader() {
params_lv:LoadVars = new LoadVars();
var owner:Loader = this;
params_lv.onLoad = function (success:Boolean) {
owner.onLoadVarsDone(success); }
params_lv.load("foo.txt");
}
function onLoadVarsDone(success:Boolean):Void {
trace(params_lv.someVariable);
}
}

Scope of the this keyword

The
keyword refers to the object in the currently executing scope. Depending on what type
this
of event handler technique you use,
Within an event handler or event listener function
event handler or event listener method. For example, in the following code,
// onPress() event handler attached to _level0.my_mc:
my_mc.onPress = function () {
trace(this); // displays '_level0.my_mc'
}
Within an on() handler attached to a movie clip
handler is attached, as shown in the following code:
on()
// Attached to movie clip named my_mc
on(press) {
trace(this); displays '_level0.my_mc'
}
176
Chapter 5: Handling Events
refers to is confused between the
this
onLoadVarsDone()
object resides in the this scope when it is invoked, even though the
params_lv
function relies on the
instance that does not exist.
onLoadVarsDone()
object is still visible in the scope of the anonymous function, so it
owner
this
onLoad
onLoadVarsDone()
event handler when the text file has
this.onLoad
function is invoked with
object by reference. Therefore, it is
params_lv
method in the scope of the Loader object, you can
can refer to different objects.
,
refers to the object that defines the
this
,
refers to the movie clip to which the
this
event handler and the class.
method will
set to LoadVars,
this
refers to
this
:
my_mc

Advertisement

Table of Contents
loading
Need help?

Need help?

Do you have a question about the FLASH MX 2004-USING ACTIONSCRIPT IN FLASH and is the answer not in the manual?

Questions and answers

Subscribe to Our Youtube Channel

This manual is also suitable for:

Flash mx 2004 - actionscript

Table of Contents