Object.prototype.someMethod

| 2 Comments

If you've been trying to get accustomed to ActionScript 2, you've probably wondered how the ActionScript 1 style ClassName.prototype.someMethod = function() {} code fits into the "big picture." This has been a hot topic of discussion lately.

Consider the following example: I want to overwrite the MovieClip method "moveTo" to reposition the MovieClip and additionally return the coordinates in an Object. Currently the moveTo method will only reposition the MovieClip without returning any information.

To accomplish the above, what we need to do is create a custom class that extends MovieClip. The reason we "extend" MovieClip is because we're creating a class that "is a" MovieClip, but contains some additional functionality not present in the MovieClip class. The additional functionality, in this case, is a different implementation of the "moveTo" method. In Object Oriented Programming, the "is a" relationship is an example of inheritance and is implemented in ActionScript 2.0 through the "extends" keyword. The class looks like this:

// CustomMC.as class CustomMC extends MovieClip { // hide the constructor from the outside world since // no one should be using it private function CustomMC() {} // override the MovieClip.moveTo method public function moveTo(x:Number, y:Number):Object { this._x = x; this._y = y; return {x:x, y:y}; } }

Now that we have our custom class created, we need to associate the class with a MovieClip symbol in the library so the symbol uses our over-ridden moveTo function and not the default MovieClip.moveTo one. Do this by right-clicking on a MovieClip in the library and selecting "Linkage...". A dialog box will appear. Check "Export for ActionScript." Then, where is says "AS 2.0 Class:", enter the name of the class to associate with the MovieClip instances on the stage. In our example, this is "CustomMC". Click ok.

That's it! Now, whenever you drag a MovieClip from the stage that is associated with the "CustomMC" class and invoke the moveTo method, the overridden moveTo method will be called instead of the "base" moveTo. The "base" class (also known as "super" class) is the class which is extended (in this case, "MovieClip"). A "subclass" "is a" "superclass". The "child" class "inherits from" the "parent" or "base" class.

A quick example:

// test_mc is the instance name of symbol associated with the "CustomMC" class // .. this call executes CustomMC.moveTo coords = test_mc.moveTo(5, 10); trace(coords.x); // 5 trace(coords.y); // 10 // test2_mc is a regular movieclip, NOT associated with the "CustomMC" class // .. this call executes MovieClip.moveTo coords2 = test2_mc.moveTo(6, 6); trace(coords2.x); // undefined, since the built in MovieClip.moveTo does not return anything

For additional information and a discussion around this topic, please see this FlashCoders thread.

2 Comments

Leave a comment

Flex.org - The Directory for Flex

Archives