Using Objects in ActionScript > Creating inherited properties |
![]() ![]() ![]() |
Creating inherited properties
You can define properties or methods of a class to be inherited, so that every instance in the class uses the same value for a property, or the same function for a method. To create an inherited property or method for a class, you use the prototype
property of the class constructor.
For example, the following code defines an inherited method, called area
, that calculates the area of an object in the class Ball:
Ball.prototype.area = function(){ return Math.PI * this.radius * this.radius; };
It is usually appropriate to define methods as inherited. Generally, methods are the same for all instances of a class. Defining the method as inherited saves memory because you define the method only once, instead of defining it separately for each instance.
Classes can inherit properties and methods from one another. You could create a new class, bouncingBall, to inherit the radius
, color
, and alpha
properties and the area()
method of the Ball class.
You can also set a class that you create to inherit the properties and methods of a built-in class. For example, you can set the Ball class to inherit the properties and methods of the built-in MovieClip class:
Ball.prototype = new MovieClip();
In this statement, the MovieClip class is a superclass, and the Ball class is a subclass. Using the Ball class, you can invoke all the properties and methods of the MovieClip class, without having to assign the properties or define the methods on the Ball class individually. Using superclasses and subclasses saves memory and can save you a lot of time in defining properties and methods for a class.
To create inherited properties or methods:
Use the following syntax to create an inherited property:
Constructor
.prototype.propertyName
=value
;
Use the following syntax to create an inherited method:
Constructor
.prototype.methodName
= function(){ // statements defining the method };
![]() ![]() ![]() |