2007年4月13日星期五

Using prototype


The prototype object in ActionScript is an object that exists among classes whose values are shared among all instances of the class to which it belongs. In ActionScript 1 and 2, it was used to control class inheritance. When a subclass instance references a variable, it first checks for that variable in the instance, followed by the class's prototype, followed by the superclass's prototype and so on through the prototype (inheritance) chain until there are no more classes.

In ActionScript 3, inheritance is primarily managed through Class inheritance and does not depend on the prototype object. However, the prototype object still exists and still provides much of the same functionality it did in AS1/AS2.

Each class and (non-method) function created in AS3 has a prototype object associated with it. For classes, prototype is read-only, meaning you cannot redefine it with a new value. However, it doesn't mean you cannot define new values within it (otherwise it would be pointless ). Function prototypes are not read only. This allows you to create dynamic classes using the old style of class definitions through functions and set up inheritance through redefining the prototype.

Example:

ActionScript Code:

package {

import flash.display.Sprite;

public dynamic class MyClass extends Sprite {

public function MyClass(){

// prototype = new Object(); // ERROR, cannot change prototype of class
prototype.newValue = 1; // OK, adding (or removing) prototyped values

trace(this.newValue); // 1
trace(prototype.toString); // function Function() {}
trace(prototype.addChild); // undefined
trace(addChild); // function Function() {}

// dynamic ("old style") class definition
var TempClass:Function = function():
void {
trace("Create TempClass");
}

TempClass.
prototype = prototype; // OK, can set up inheritance

var tempObject:* = new TempClass();
// "Create TempClass"

trace(tempObject.newValue); // 1
}
}
}



Note that you should always prefix dynamic variable references with the this keyword. Also note that the Object class methods are dynamic and are defined in the prototype (which is why they are not overridden with the override keyword). You may also notice that the tempObject is typed as * instead of TempClass. This is because TempClass is only recognized as being a Function in AS3, not an actual class though it can still be used as one. Though a Class type exists, dynamic classes created like TempClass will always be recognized as Functions so creating instances with them always generates instances typed as a generic object.

0 评论: