How to build an Object-Oriented ActionScript 3 Preloader in Flash CS4: 2 Methods

June 20th, 2009

The magic of creating a preloader in ActionScript 3 lies in the LoaderInfo class. Every instantiated DisplayObject instance (all objects that appear on the stage, plus the stage itself) have a loaderInfo property that returns a LoaderInfo instance that contains information about the loading progress of that particular display object. Creating a preloader for the whole application is a matter of monitoring these LoaderInfo instances.

Method 1: Monitor Stage LoaderInfo instance

Under this method the loading progress is monitored via the LoaderInfo instance associated with the stage. Since all assets that will appear in the application need to be attached to the stage, the stage’s LoaderInfo instance will reflect the loading of all these assets.

Graphics

  1. Go to File → New… and select Flash File (ActionScript 3.0).
  2. Using the Rectangle tool create a rectangle (include a stroke) on the stage that is 100 pixels wide by 10 pixels high.
  3. Click on the fill of the newly created rectangle and select Modify → Convert to Symbol… Name the new instance ProgBar and set the registration point to left-middle. This will be the progress bar of the preloader.

    preloader_pbar

  4. With the new ProgBar instance selected on the stage, go to the Properties panel and name the instance progBar.
  5. Select the whole rectangle (stroke and progress bar instance). Select Modify → Convert to Symbol… Name the new instance Preloader and set the registration point to left-middle. Check the Export for ActionScript button.
  6. Click OK. If you get a warning that says the “definition for this class could not be found” click OK again.
  7. With the new Preloader instance selected, go to the Properties panel and name the newly created instance preloader. Your library should look like the following:

    preloader_library

  8. Select frame 2 of the main timeline, go to Insert → Timeline → Blank Keyframe. All content for the application will appear on frame 2 and beyond.
  9. Go to Insert → New Symbol… Name the new instance Content. If you check Export for ActionScript be sure to uncheck Export in frame 1, otherwise the preloader will not function properly.
  10. Place all content of the application on the timeline of the newly created Content instance.
  11. Return to the main timeline. Select frame 2 and drag an instance of the Content symbol from the library and place it on the stage.
  12. In the Properties panel of the stage name the document class Main. If you get a warning that says the “definition for this class could not be found” click OK.

    preloader_docclass

  13. Save the file.

Code

  1. Go to File → New… and select ActionScript File.
  2. Paste the following code and save the file as Preloader.as in the same directory as the .fla file saved earlier.
    package
    {
    	import flash.display.Sprite;
    	import flash.display.LoaderInfo;
    	import flash.events.Event;
     
    	public class Preloader extends Sprite
    	{
    		/**
    		* Alias for stage LoaderInfo instance
    		*/
    		private var _targetLoaderInfo:LoaderInfo;
     
    		/**
    		* The percent loaded
    		*/
    		private var _loadPercent:Number = 0;
     
    		/**
    		* Constructor
    		* Listen for when the preloader has been added to the stage 
    		* so that the progress of the remaining load can be monitored.
    		*/
    		public function Preloader()
    		{
    			this.addEventListener( Event.ADDED_TO_STAGE , _init );
    		}
     
    		/**
    		* Initialize variables.
    		* Set initial width of the progress bar to 0 
    		* and listen for enter frame event.
    		*/
    		private function _init(evt:Event):void
    		{
    			_targetLoaderInfo = stage.loaderInfo;
     
    			progBar.scaleX = 0;
     
    			this.removeEventListener( Event.ADDED_TO_STAGE , _init );
    			this.addEventListener(Event.ENTER_FRAME, _onCheckLoaded);
    		}
     
    		/**
    		* Check the status of the load, once complete dispatch a complete event.
    		*/
    		private function _onCheckLoaded(evt:Event):void 
    		{
    			_loadPercent = _targetLoaderInfo.bytesLoaded / _targetLoaderInfo.bytesTotal;
    			progBar.scaleX = _loadPercent;
    			if (progBar.scaleX == 1)
    			{
    				this.removeEventListener(Event.ENTER_FRAME, _onCheckLoaded);
    				this.dispatchEvent( new Event(Event.COMPLETE) );
    			}
    		}
    	}	
    }
  3. Go to File → New… and select ActionScript File a second time.
  4. Paste the following code and save the file as Main.as in the same directory as the .fla file saved earlier.
    package 
    {
    	import flash.display.MovieClip;
    	import flash.events.Event;
     
    	public class Main extends MovieClip 
    	{
    		/**
    		* Constructor
    		* Stop timeline and add event listener to preloader.
    		*/
    		public function Main() 
    		{
    			this.stop();
    			preloader.addEventListener( Event.COMPLETE , _initContent );
    		}
     
    		/**
    		* Load has finished, remove preloader and preceed to next frame.
    		*/
    		private function _initContent(evt:Event):void 
    		{
    			preloader.removeEventListener( Event.COMPLETE , _initContent );
    			this.removeChild(preloader);
    			nextFrame();
    		}
    	}
    }
  5. To test the preloader go to Control → Test Movie. Go to View → Simulate Download.
  6. Download method 1 complete source

Method 2: Monitor content SWF LoaderInfo instance

Under this method two SWFs are created, one encapsulating the preloader and the other encapsulating all content. The content SWF is loaded inside of the preloader SWF, which monitors the loading progress.

Graphics

  1. Follow steps 1 – 7 in the previous method.
  2. In the Properties panel of the stage name the document class PreloaderWrapper. If you get a warning that says the “definition for this class could not be found” click OK.
  3. Save the file.
  4. Go to File → New… and select Flash File (ActionScript 3.0).
  5. Add the content for your application to the timeline of this file.
  6. Save the file as content.fla.
  7. Go to Control → Test Movie to create the content.swf that will be loaded by the preloader SWF.

Code

  1. Go to File → New… and select ActionScript File.
  2. Paste the following code and save the file as PreloaderWrapper.as in the same directory as the .fla file saved earlier.
    package 
    {
    	import flash.display.Sprite;
    	import flash.display.Loader;
    	import flash.display.LoaderInfo;
    	import flash.display.DisplayObject;
    	import flash.events.Event;
    	import flash.events.ProgressEvent;
    	import flash.net.URLRequest;
     
    	public class PreloaderWrapper extends Sprite 
    	{
    		/**
    		* Alias for content LoaderInfo instance
    		*/
    		private var _targetLoaderInfo:LoaderInfo;
     
    		/**
    		* The percent loaded
    		*/
    		private var _loadPercent:Number = 0;
     
    		/**
    		* Constructor
    		* Creates Loader instance, adds event listeners and begins loading content SWF.
    		*/
    		public function PreloaderWrapper() 
    		{
    			var loader:Loader = new Loader();
    			_targetLoaderInfo = loader.contentLoaderInfo;
    			_targetLoaderInfo.addEventListener( ProgressEvent.PROGRESS, _loadingData );
    			_targetLoaderInfo.addEventListener( Event.COMPLETE , _finishedLoading );
    			loader.load( new URLRequest("content.swf") );
     
    		}
     
    		/**
    		* Monitor loading progress and update progress bar.
    		*/
    		function _loadingData( evt:ProgressEvent ):void 
    		{
    			_loadPercent = _targetLoaderInfo.bytesLoaded / _targetLoaderInfo.bytesTotal;
    			preloader.progBar.scaleX = _loadPercent;	
    		}
     
    		/**
    		* Remove event listeners and preloader, and attach content SWF to stage.
    		*/
    		function _finishedLoading( evt:Event ):void 
    		{
    			_targetLoaderInfo.removeEventListener( ProgressEvent.PROGRESS, _loadingData );
    			_targetLoaderInfo.removeEventListener( Event.COMPLETE , _finishedLoading );
    			this.removeChild(preloader);
    			this.addChild( DisplayObject(LoaderInfo(evt.target).content) );
    		}
    	}
    }
  3. To test the preloader go to Control → Test Movie. Go to View → Simulate Download.
  4. Download method 2 complete source

Learning Flash CS4 Professional published

May 5th, 2009

learncs4

Once again I had the pleasure of working as a technical editor with O’Reilly Media and author Rich Shupe on his latest title, Learning Flash CS4 Professional. It has just recently been published. Check it out!

Lessons from 1 year of blogging

May 1st, 2009

oneyear This blog just turned 1 year old today, how neat! In celebration of one year of blogging, here are 5 reasons why you should start a blog:

  1. It helps you clarify your thoughts – Nothing makes something clearer in your own head than writing it down for others to read.
  2. It is your public portfolio and resume – Move back through these posts and you will see my areas of expertise and what discipline I am working in at any given time.
  3. It’s a repository of useful links and resources – Want to store a link or a useful tidbit of information where you can easily find it again? Blog it.
  4. It allows you to share your ideas and thoughts – Ask questions of your readers, share links to your most useful posts elsewhere. A blog isn’t just about one-way communication.
  5. It brings a worldwide audience to your doorstep – After the United States, my second greatest number of visitors are from India. It’s always good to be reminded that while we live on a globe with a vast array of different cultures, we retain common interests across them.

FITC Toronto 2009 Recap

April 30th, 2009

fitclogoMy third pilgrimage to Toronto to attend FITC has come and gone. Knowing the routine of the conference made this the best one yet for me. I finished off my deck of old business cards from last year and filled my wallet with a stack of cards from others.

Here are few notes and links:

  • For me, the conference kicked off with Alec Cove’s Beautiful Algorithms: Design from Nature and Mathematics, which fell in the thematic vein of sessions I’ve seen from Keith Peters and Grant Skinner, which described beautiful algorithms inspired by or mimicking nature.
  • The Adobe keynote on day one was a tad disappointing as it was filled with what was (to me and those I talked to) old news. I did pick up one link from it when Justin Everett-Church demoed an interesting augmented reality piece by Goodby, Silverstein & Partners for GE—a piece which later won at the FITC award show. See it here (use FireFox, I had issues in Safari). A great interactive piece, though for a site promoting more environmentally friendly energy practices, the requirement to print out a piece of paper for the sole purpose of interacting with the site seemed disappointingly off message.
  • Another Adobe session covering Adobe Flash Catalyst was an interesting introduction to this product, which I’m sure I’ve not seen the last of. Some features, such as the four pre-defined states of a button and existence of a timeline (though time, not frame, based thankfully) were reminiscent of the Flash IDE.
  • Check out SourceBinder, a node-based programming environment. Build programs visually by linking nodes of functionality together. Also, VizualPV3D, a GUI interface for laying out PaperVision3D scenes.
  • Grant Skinner’s Things Every Flash Developer Should Know was one of my favorite sessions of the conference. Well prepared and refined, as I’ve come to expect from Grant’s presentations. Check it out online here.
  • There were a number of frameworks shown this year, two I hadn’t previously heard of:

    • Gaia Flash Framework, for quickly building mini-sites (showcase-style sites was my impression)
    • Moccasin – “Flex framework for visual object-based editor applications.”

    Additionally, there was a session on PureMVC, which was to be presented by its inventor, Cliff Hall, but was instead covered by someone else whose name I failed to jot down.

  • The final general session was an engaging presentation by Jared Ficklin of Frog Design, who taught much about sound and sound visualization through his hour talk/flame-and-smoke-machine-laden-sine-wave-surfin-act. A very fun session :) . Within his presentation, Jared showcased the work of the talented Annika Hamann at Das Plankton, creator of some remarkable sound visualization work housed at foulowl.com.

Object-Oriented JavaScript Tip: Implementing the Singleton Pattern

April 21st, 2009

The Singleton design pattern is a development approach that ensures only a single instance of a particular class is available in a system. Imagine building the game of chess, you would only want there to be one instance of the board floating around—say an instance of a class called ChessBoard. The Singleton pattern ensures that there will only ever be one ChessBoard object available in your game.

Often the implementation of a Singleton looks something like this:

function Singleton()
{
}
 
Singleton.getInstance = function( )
{
	if (Singleton.instance == undefined) Singleton.instance = new Singleton();
	return Singleton.instance;
}

However, this is a port to JavaScript from other languages and it doesn’t offer a very robust implementation of the Singleton. For example, this design relies on calling Singleton.getInstance() to retrieve the single instance. However, nothing prevents calling…

var instance1 = new Singleton();
var instance2 = new Singleton();
alert( instance1 == instance2 ); // outputs false because these are two object instances

…to create two instances, defeating the pattern. A better approach is to encapsulate the Singleton constructor function in a variable and return a reference to the function rather than the instance, and then provide access to the instance via a getInstance method as above.

var Singleton = new function Singleton() 
{
	var instance = this;
	Singleton.getInstance = function()
	{
		return instance;
	}
}

In this case, the code shown earlier does not break the pattern:

var instance1 = new Singleton();
var instance2 = new Singleton();
alert( instance1 == instance2 ); // outputs true because these refer to the same constructor function

However, this just prevents circumvention of the pattern, the same object instance has not yet been retrieved. To do this the static getInstance() method is called on the constructor reference variable.

var instance1 = Singleton.getInstance();
var instance2 = Singleton.getInstance();
alert( instance1 == instance2 ); // outputs true because these refer to the same object instance

Additionally, a toString method, as well as static and instance methods (though both are functionally identically in this case since there’s only one instance available) can be built into the Singleton definition, like so:

var Singleton = new function Singleton() 
{
	var instance = this;
	Singleton.getInstance = function()
	{
		return instance;
	}
	this.toString = function()
	{
		return "[object Singleton]";
	}
 
	this.instanceMethod = function()
	{
		alert( "instance method called!" );		
	}
 
	Singleton.staticMethod = function()
	{
		alert( "static method called!" );
	}
	return Singleton;
}

Try these out:

Singleton.staticMethod();
Singleton.getInstance().instanceMethod();

Since JavaScript is a prototype-based language (not actually having classes), additional functionality can be added through the Singleton’s prototype, as in:

Singleton.prototype.custFunct = function(){ alert( "A custom method" ); } // add instance method
Singleton.getInstance().custFunct(); // call new instance method

Object-Oriented JavaScript Tip: Creating static methods, instance methods

April 9th, 2009

Custom JavaScript objects can have instance methods (function that are associated with a particular JavaScript object), but like other Object-Oriented languages, they can also have static methods, that is functions that are associated with the JavaScript class that created an object, as opposed to the object itself. This is useful in cases where a function (a.k.a. a method) will not be different in different object instances. Let’s look at an example…

Suppose you created a class to handle simple arithmetic calculations:

function Calculator()
{
 
}

To begin with, an instance method could be added to this class in one of two ways, either inside the constructor or through the class prototype. In this example, one method called multiply will be created, which returns the product of two values multiplied together. First, implemented in the constructor it looks like:

function Calculator()
{
	this.multiply = function(val1 , val2)
	{
		return (val1*val2);
	}
}

Via the class prototype, which is a more readable solution in my opinion, it would look like:

function Calculator()
{
}
 
Calculator.prototype.multiply = function(val1 , val2)
{
	return (val1*val2);
}

Use of this method would then occur through instances of the Calculator class, like so:

var calc = new Calculator();
alert( calc.multiply(4,3) ); //pop-up alert with product of 4 times 3

However, it shouldn’t really be necessary to create an object to use the multiply method, since the method isn’t dependent on the state of the object for its execution. The method can be moved to the class to clean up this code a bit. First the class definition is created, which looks almost identical to the instance method declaration above, with the exception of the prototype keyword being removed:

function Calculator()
{
}
 
Calculator.multiply = function(val1 , val2)
{
	return (val1*val2);
}

Now the multiply method can be called through the class itself, instead of an instance of the class, like so:

alert( Calculator.multiply(4,3) ); //pop-up alert with product of 4 times 3

Object-Oriented JavaScript Tip: Overriding toString() for readable object imprints

April 5th, 2009

JavaScript has a core Object class that contains a toString() method that is called whenever a request is made to convert an object to a string (like related ECMAScript-based ActionScript). This is often done during debugging to check that a variable actually contains a reference to a certain object.

Most likely alert(myObj) or console.log(myObj) would be used, for example:

var myObj = new Object()
alert(myObj); // popup displays [object Object]

The problem is if you create a custom object. In this case it would be ideal to adjust the string representation to reflect the fact that the custom object is different from the core object. By default there is no difference, as the following example demonstrates:

// custom Foo class
function Foo() 
{	
}
 
// new Foo object instance
var f = new Foo();
alert(f);  // popup displays [object Object]

To make this more readable, add a toString() method to the prototype of the object:

function Foo() 
{
}
 
// toString override added to prototype of Foo class
Foo.prototype.toString = function()
{
	return "[object Foo]";
}
 
var f = new Foo();
alert(f);  // popup displays [object Foo]

In this case, because of the presence of the toString() method, which overrides the default, a custom string can be displayed for the object that is more applicable to what it is. Additionally, information about the properties of the object could be included in this method as well, as in:

function Foo() 
{
	this.message = "Hello World!";
}
Foo.prototype.toString = function()
{
	return "[object Foo <" + this.message + ">]";
}
 
var f = new Foo();
alert(f);  // popup displays [object Foo <Hello World!>]

Common Flash Compiler Errors: #1046

March 25th, 2009

This error shows the following in the Compiler Errors window:


1046: Type was not found or was not a compile-time constant: [Class name].

Quick Answer and Solution

Where I have “[Class name]” above you will have any number of names listed, for example it may say Event, Sprite, TextField, etc. What this means is you are using a piece of code that utilizes a class (typically seen as files with a “.as” extension) that you have not “imported” so that your code knows where to find it. To fix this problem perform the following:

  1. Open a web browser and navigate to Google.
  2. Enter the search “[class name] actionscript 3 site:livedocs.adobe.com” (replacing [class name] with whatever the class name is in the error message, such as TextField, MouseEvent, URLLoader, etc.). For example, “Event actionscript 3 site:livedocs.adobe.com”
  3. Look for a search result that lists the class in a format of a series of words with dots between them, probably will be the top result. Examples include:
    • flash.events.Event
    • flash.display.Sprite
    • fl.transitions.Tween
    • flash.geom.Rectangle

    This is the path to the class, which you can use to import the class into your code.

  4. Without clicking on the search result, copy the class name as it appears in the previous step.
  5. Return to Flash and double-click the error message.
  6. Scroll to the top of the code area. Type “import” and paste the path to the class. For example,
    import flash.events.Event;

If you are using code on the Timeline, this can be placed at the top of the Actions panel. If you have written a class file that is referencing another class, this code appears between the package { curly brace, and class declaration, public class MyClass.

For example,

package
{
	// class import statements appear here
	import flash.display.MovieClip;
 
	public class Main extends MovieClip
	{
		public function Main()
		{
		}
	}
}

Technical Overview

A class file is an external text file that contains variables and functions (known as properties and methods in the object-oriented programming context), essentially this means class files are self-contained blocks of code that contain code related to a particular task. To access these variables and functions within your own block of code the class file needs to be imported. If your code contains any references to a class file that has either: (a) not been imported, or (b) is not within the same folder as your .fla or .as files, then a #1046 error will be thrown. For example, suppose you have the following class file declared for a button:

package
{
	import flash.display.MovieClip;
 
	public class MyButton extends MovieClip
	{
		public function MyButton()
		{
			this.addEventListener( MouseEvent.CLICK , _clicked );
		}
 
		private function _clicked( evt:MouseEvent ) : void
		{
			// button was clicked!
		}
	}
}

Testing this code would produce the following error:

1046: Type was not found or was not a compile-time constant: MouseEvent.

With the source listed as…

private function _clicked( evt:MouseEvent ) : void

This is because the class MouseEvent is referenced in the code, but is not imported at the top of the class file. The fix is simple and looks like this:

package
{
	import flash.display.MovieClip;
	// import the MouseEvent class
	import flash.events.MouseEvent;
 
	public class MyButton extends MovieClip
	{
		public function MyButton()
		{
			this.addEventListener( MouseEvent.CLICK , _clicked );
		}
 
		private function _clicked( evt:MouseEvent ) : void
		{
			// button was clicked!
		}
	}
}

Typically if you are a beginning ActionScripter, you will run into this error when referencing classes created by Adobe. However, as you become more advanced in your scripting abilities you may place your own custom class files in “packages” that would then need to be imported using the same above process. In case you are wondering what the stuff is before the actual class name, such as “flash.display” and “flash.events,” this is the “package” that class resides in, which is essentially the folders the class file resides in on disk. For example, suppose I created a class called “MyButton” and placed it in the package “com.anselmbradford.” This class would appear in a text file called “MyButton.as” that would be in a folder called “anselmbradford” that would itself be in a folder called “com.” The class file would look like:

package com.anselmbradford
{
	import flash.display.MovieClip;
 
	public class MyButton extends MovieClip
	{
		public function MyButton()
		{
		}
	}
}

To import this class file into another class file I would place the “com” folder (containing the class file two levels in) in the same directory as my .fla or .as file that I wanted to import this class into. I would then import it using the syntax shown previously. For example:

package
{
	import flash.display.MovieClip;
	// class is imported
	import com.anselmbradford.MyButton;
 
	public class Main extends MovieClip
	{
		public function Main()
		{
			// class is referenced in code, so must be imported
			var button:MyButton = new MyButton();
		}
	}
}

Note: Whole sets of class files that are within the same package can be imported using the “*” wildcard operator. For example, flash.events.Event, and flash.events.MouseEvent, both reside in the flash.events package. Instead of having two lines to import both of these classes, you can have import flash.events.*;, which will import all the necessary classes from the flash.events package.

The ever-evolving interactive web space: Microsoft’s Silverlight initiative, Google’s love of JavaScript, Adobe’s comfortably massive Flash Platform

March 19th, 2009

Microsoft’s Web design and development conference, MIX09, is currently happening in Las Vegas, Nevada. As is tradition with major corporate-backed events such as this one, a slew of new products were released. Of note is the Silverlight 3 beta (available here, but it sounds like it is very much a preview). The new features are extensive and—for many of them—sound very Flash-esque (Ryan Christensen’s site provides a nice write up of the new features). Along with Silverlight, Internet Explorer 8 was released out of beta, and thankfully sounds to be the most standards-compliant Internet Explorer version to date. It is foreseeable that if Microsoft were able to bundle the Silverlight plugin with a standard’s compliant browser that gained broad support from developers—without raising the eyebrows of antitrust regulators—that Flash would be presented with its greatest obstacle in maintaining its present dominance in the interactive website space.

In the mean time, while Adobe and Microsoft develop increasingly similar looking products, Google and open source initiatives such as JQuery UI are moving JavaScript beyond a mere scripting language. Google has launched a site called Chrome Experiments, which showcases contemporary interactive pieces built entirely in JavaScript. Many are quite impressive, for example, this piece could easily be a Flash piece (turn your speakers on). I noticed Flash master Mr. Doob has a piece up there too. The about page begins “We think JavaScript is awesome.” I’ve been playing with JQuery UI recently and I do have to admit it has come a long way from what JavaScript was capable of when I really seriously last played with it in the late 90’s.

At any rate it’s exciting to see the explosion of possibilities all these projects will bring. More than ever the Web feels like the digital frontier.

Common Flash Compiler Errors: #1042

March 19th, 2009

This error shows the following in the Compiler Errors window:


1042: The this keyword can not be used in static methods. It can only be used in instance methods, function closures, and global code.

Quick Answer and Solution

Most likely you are you using the keyword “this” inside a class file, but it is not inside the curly braces of a function. By double-clicking on the error it will take you to the offending line of code. Check carefully to make sure where you have placed the keyword “this” is actually between the opening “{” and closing “}” braces of a function declaration. If it looks correct, but is accompanied by error #1126 (described here), then fix that error first. Also, if the “this” keyword appears in a function that has the “static” keyword in its declaration, error #1042 will also be thrown.

The following are three scenarios where a class file will throw this error:

package
{
	import flash.display.MovieClip;
 
	public class Main extends MovieClip
	{
		public function Main()
		{
		}
		// "this" keyword used outside a function
		this.visible = false;
	}
}
package
{
	import flash.display.MovieClip;
 
	public class Main extends MovieClip
	{
		public function Main()
		{
		}
 
		// function does not have a body because of misplaced semicolon,
		// so error #1126 is thrown
		public function hide():void;
		{
			// the "this" keyword is actually not in the body of a function
			// because of the above #1126 error
			this.visible = false;
		}
	}
}
package
{
	import flash.display.MovieClip;
 
	public class Main extends MovieClip
	{
		public function Main()
		{
		}
 
		// function is a "static method," meaning it runs inside the class,
		// not the object created from the class
		static public function hide():void
		{
			// the "this" keyword is inside a static method
			this.visible = false;
		}
	}
}

The corrected form of the above examples would be:

package
{
	import flash.display.MovieClip;
 
	public class Main extends MovieClip
	{
		public function Main()
		{
		}
 
		public function hide():void
		{
			// the reference to "this" is inside a non-static function
			// (called an instance method)
			this.visible = false;
		}
	}
}

Technical Overview

There are two types of methods (functions) that can appear in a class file, static methods and instance methods. Static methods refer to methods that are run via the class itself, while instance methods refer to methods run via an instance of the class. Consider the following class file:

package
{
	import flash.display.MovieClip;
 
	public class Main extends MovieClip
	{
		public function Main()
		{
		}
 
		static public function staticMethod():void
		{
			trace( "static method called!" );
		}
 
		public function instanceMethod():void
		{
			trace( "instance method called!" );
		}
	}
}

To call the first method, a new “Main” object does not need to be created, as the static method can be called on the class itself, like so:

Main.staticMethod();

Conversely, to access the other method, an (object) instance of the Main class needs to be created and then the method can be called through that object, like so:

var main:Main = new Main();
main.instanceMethod();

Use of the “this” keyword refers to the object instance of the class that the code is currently dealing with (in the above case if this appeared in the body of the instanceMethod() method it would be referring to the object placed in the main variable). Since no object instance has to be created to use static methods, the “this” keyword can not be used within those methods because there is no object in existence to refer to. Additionally, all code outside of a function declaration runs before an object instance is created (before the constructor function runs), so any references to “this” do not have an object to refer to in that context either.