Main Content

You are here:

Constructor functions

Today we'll be touching on another on another ActionScript concept - the idea of constructor functions. Like most of our more recent free Flash tutorials, it's more applicable to AS3 than AS2, but could really be applied to either, or even an entirely different programming language.

Firstly, don't panic! - it might look long and boring, but most of it you will already be familiar with.

The theory

As a general rule, constructor functions - commonly shortened to constructors - run when an object is created from a class. The new object, opening its eyes to the world, will probably want to do some stuff before it receives any other commands. In practice, they are usually used for setting variables. Let's look at the two main applications in Flash of these constructors.

Application in normal classes

This is perhaps the easier of the two to explain. Remember when we created a doorman called 'Andy'? No? You can read about that here, then. But anyhow, he had our class, which we called 'Doorman' and our object, 'Andy' who was an instance of a doorman.

Last time around, Andy didn't say anything when we created him, we had to force him to using a separate function:

public class Doorman{
        public function sayHello(nameof:String):String{
                var greeting:String = "Hello "+nameof;
                return greeting;
        }
}

But what if we wanted to know if he had been created correctly?

public class Doorman{
        public function Doorman(){
                trace("Ready and waiting, sir!");
        }
        public function sayHello(nameof:String):String{
                var greeting:String = "Hello "+nameof;
                return greeting;
        }
}

That's much better. But what have we done? Well, we've added a new function. Importantly, it has the same name as the class - denoting it as a constructor and will be called every time a new doorman is created, tracing our message.

Constructors must be "public", not return anything, but can take arguments. If you're not quite there yet, think about the line:

var myTimer:Timer = new Timer(1000,10);

Here, you pass two arguments to the constructor of the Timer class.

Application in a document class

The constructor in a document class is the bit automatically run when the SWF is compiled, and the focus of a great deal of the code we look at in other Foundation Flash tutorials.

You can't require arguments of a document class, as the compiler wouldn't know what to pass to the function.

Well, I hope that's clarified the area a bit, and that all the questions about constructors have been answered. If they haven't use the comments box below, of the contact link above.

Harry

Comments