ActionScript 3 Understanding the "Error 1009: Cannot access a property or method of a null object reference" Stage is unavailable


Sometimes developers write some code that desires access to stage, or Flash stage, to add listeners. It can work for the first time, then all of a sudden fail to work and produce the error 1009. The code in question can even be on the timeline, as it's the first initiative to add code there, and many tutorials that still exist use timeline code layer to place the code.

public class Main extends MovieClip {
    public function Main() {
        stage.addEventListener(Event.ENTER_FRAME,update); // here

The reason this code doesn't work is simple: A display object is first instantiated, then added to the display list, and while it's off the display list, stage is null.

Worse if the code like this:

stage.addEventListener(Event.ENTER_FRAME,update); // here

is placed on the timeline. It can even work for some time, while the Main object is slapped to stage via GUI. Then, their SWF is loaded from another SWF, and all of a sudden the code breaks. This happens because the Main's frames are constructed in a different way when the SWF is loaded directly by the player and when the loading is processed asynchronously. The solution is to use Event.ADDED_TO_STAGE listener, and put all code that addresses stage in it, and put the listener itself into an AS file instead of the timeline.