About scope in classes
When you port code to ActionScript 2.0 classes, you might have to change how you use the
keyword. For example, if you have a class method that uses a callback function (such as
this
the LoadVars class's
onLoad
the class or to the LoadVars object. In this situation, you might need to create a pointer to the
current class, as the following example shows:
class Product {
private var m_products_xml:XML;
// Constructor
// targetXmlStr contains the path to an XML file
function Product(targetXmlStr:String) {
/* Create a local reference to the current class.
Even if you are within the XML's onLoad event handler, you
can reference the current class instead of only the XML packet. */
var thisObj:Product = this;
// Create a local variable, which is used to load the XML file.
var prodXml:XML = new XML();
prodXml.ignoreWhite = true;
prodXml.onLoad = function(success:Boolean) {
if (success) {
/* If the XML successfully loads and parses,
set the class's m_products_xml variable to the parsed
XML document and call the init function. */
thisObj.m_products_xml = this;
thisObj.init();
} else {
/* There was an error loading the XML file. */
trace("error loading XML");
}
};
// Begin loading the XML document
prodXml.load(targetXmlStr);
}
public function init():Void {
// Display the XML packet
trace(this.m_products_xml);
}
}
Because you are trying to reference the private member variable within an
keyword actually refers to the
this
might expect. For this reason, you must create a pointer to the local class file so that you can
directly reference the class from the
For more information on classes, see
more information on scope, see
750
Best Practices and Coding Conventions for ActionScript 2.0
method), it can be difficult to know if the
instance and not to the
prodXml
handler.
onLoad
"Understanding classes and scope" on page
"Handling scope" on page
keyword refers to
this
onLoad
class, which you
Product
747.
handler, the
283. For
Need help?
Do you have a question about the FLASH 8-LEARNING ACTIONSCRIPT 2.0 IN FLASH and is the answer not in the manual?