PDA

View Full Version : Classes



Mr beef
September 17th, 2008, 07:43 PM
Right, I haven't touched AS in a few months now so now I have returned to it I am just as lost when I first started lol.

I think of classes as a way to reuse the same code but creating different things. So for example a class called Items which gives the traits for all things created by that class, they are all an Item but all differ slightly.

So I quickly went off to make a class;
class Test {
var number:Number;
public function getTrace() {
number = Math.round(Math.random()*1000);
trace(number);
}
}

And made a swf;
var Test:Test = new Test();
var Test3:Test = new Test();
var Test2:Test = new Test();

_root.Test3.getTrace();
_root.Test2.getTrace();
_root.Test.getTrace();


But I only get one trace given to me, but if I swap the order so it goes Trace 3, then 2 then 1 I get three traces as I want. I think I have misunderstood something simple :crying: Why does it do that? I just wanted 3 different items to do the same thing, like 3 swords which you can all pickup, sell equip etc etc.

Smee
September 17th, 2008, 10:24 PM
var Test:Test = new Test();

You're using the name of the class as the instance name, which is causing the rest of them to be undefined and so they don't even have a 'getTrace' method. You can see it with this code:


var Test:Test = new Test();
var Test2:Test = new Test();
var Test3:Test = new Test();

trace(Test2); // Output: "undefined"
trace(Test3); // Output: "undefined"

Use a unique name for the first one:


var Test1:Test = new Test();
var Test3:Test = new Test();
var Test2:Test = new Test();

_root.Test3.getTrace();
_root.Test2.getTrace();
_root.Test1.getTrace();

Ranoka
September 18th, 2008, 06:40 AM
By convention classes begin with a capital letter.
So it can be confusing to start variables with capital letters because glancing at your code later on you may think that a variable is a class.

Mr beef
September 20th, 2008, 04:03 PM
Would just like to thank people for the help, and err the spam above...ignore it lol. I will start digging in classes again later just need to relax after today's work :P