OOP4AS#3: Constructors

Installment 3 will build on the previous 2 parts (so if you haven’t read them already, you should), by taking a look at how to create a constructor function for a class in ActionScript 2.0.

A constructor lets you pass in parameters when you create a new instance of a class, and use those parameters to set properties and carry out operations on the new instance as it’s created.

Read on…

To create a constructor for a class, you simply define a function inside the class statement with exactly the same name as the class (don’t forget AS2 is case sensitive). This function is defined exactly the same as any other method for the class, but it cannot return a value. For example, if I wanted to add a constructor to my GThing class that would let me specify the myName property during instantiation, I would do it something like this:

class GThing {
var myName:String;
function getGreeting(p_salutation:String):String {
return p_salutation+" "+myName;
}
// define the constructor:
function GThing(p_myName) {
// set this instance's myName property:
myName = p_myName;
}
}

Now, in the FLA, you can do this:

var myG:GThing = new GThing("Biff Spaceman");
trace(myG.getGreeting("Yo");
// traces "Yo Biff Spaceman"
trace(myG.myName);
// traces "Biff Spaceman"

Wow, that was a pretty simple installment! I bet you feel gypped… well, you shouldn’t, it’s free. 🙂

More to come… check back often.

Grant Skinner

The "g" in gskinner. Also the "skinner".

@gskinner

10 Comments

  1. Thanks so much for the free tidbits of information regarding ActionScript 2.0. I wished I was privy to this sort of information when MX first came out about components. It is nice to get a sneak peek and understand how things work before getting your paws on something. Thanks again Grant!

  2. Grant, you are my hero.

  3. The constructor cannot return anything because a constructor has to return a new instance of the class;

    e.g. x = new String(); // x is now an instance of String.

  4. little mistake in given code:

    trace(myG.getGreeting(“Yo”);

    must be:

    trace(myG.getGreeting(“Yo”));

  5. OOP para AS2 #3 : constructores

    Esta página es una traducción de un artículo publicado por Grant Skinner, publicado en este blog.

    los ejemplos de este capĂ­tulo serán creados con la base de los dos capĂ­tulos anteriores (asĂ­ que si no los has leĂ­do, deberĂ­as hacerlo). Veremos como cre…

  6. This article is now available in german!

    Check it out at:

    http://www.urbanspice.de/blog/archives/000011.html#more

  7. Yes, translated this article also in Dutch. It can be found over here: http://www.flashpro.nl/detail.asp?ID=136

Comments are closed.