Classes and Object-Oriented Programming

It’s not uncommon to create dozens of complex objects that store rich information about everything from products in a shopping-cart system to bad guys with artificial intelligence in a video game. To expedite the creation of objects and to define object hierarchies (relationships between objects), we use object classes. A class is a template-style definition of an entire category of objects. As we learned in the introduction, classes describe the general features of a specific breed of objects, such as “all dogs have four legs.”

Object Classes

Before we see how to use classes, let’s see how things work when we don’t use them. Suppose we want a ball object, but instead of using a class to generate it, we simply adapt a generic object of the built-in Object class. We give the object these properties: radius, color, xPosition, and yPosition. Then we add two methods—moveTo( ) and area( )—used to reposition the object and to determine the amount of space it occupies.

Here’s the code:

var ball = new Object( );
ball.radius = 10;
ball.color = 0xFF0000;
ball.xPosition = 59;
ball.yPosition = 15;
ball.moveTo = function (x, y) { this.xPosition = x; this.yPosition = y; };
ball.area = function ( ) { return Math.PI * (this.radius * this.radius); };

That approach gets the job done but has limitations; every time we want a new ball-like object, we have to repeat the ball-initializing code, which is tedious and error-prone. In addition, creating many ball objects ...

Get ActionScript: The Definitive Guide now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.