PDA

View Full Version : Classes - Quick Question



Dan0
July 21st, 2007, 01:58 PM
Hey
If I have one Main class that initiates a second class like this:

Main.as
package {
public class Main extends Sprite {
function Main() {
var a = new SecondClass
}
public function coolStuff() {
trace("A");
}
}
}

SecondClass.as
package {
public class SecondClass extends Sprite {
function SecondClass() {
//do the coolStuff function in the Main class
}
}
}

How do I get my SecondClass to call the coolStuff function in the Main class? I tried doing somthing like "Main.coolStuff()" or "parent.coolStuff()" but it does not inherit and I can not be bothered with inheritance because I do not want to script my stuff like that. For example, I want a textFormat class to be defined on the Main class but used in all classes in my code, how do I do this? Im sorry to ask such a noob question but Im new to OOP and scripting ideas like this.

Thanks for your help,
Dan

Sirisian
July 21st, 2007, 04:41 PM
easy, pass it a reference.

package {
public class SecondClass extends Sprite {
function SecondClass(e:Main):void {
e.CoolStuff();
}
}
}then in the Main class:

package {
public class Main extends Sprite {
function Main():void {
var a = new SecondClass(this);
}
public function CoolStuff():void {
trace("A");
}
}
}then in the SecondClass constructor it will call CoolStuff using it's reference to Main. Note you can do:

package {
public class SecondClass extends Sprite {
public var e:Main;
function SecondClass(e_:Main):void {
e = e_;
e.CoolStuff();
}
}
}

package {
public class Main extends Sprite {
public var a:SecondClass;
function Main():void {
a = new SecondClass(this);
}
public function CoolStuff():void {
trace("A");
}
}
}
that would allow an instance of SecondClass to be used throughout the Main function without having to pass a reference everytime SecondClass needed something Main had.

Also why is SecondClass derived from a Sprite object? If it doesn't need the abilities of Sprite don't inherit from it.

Dan0
July 21st, 2007, 05:08 PM
Thanks for the brilliant reply.
One thing tho; how come its so hard to do this. In my mind it makes sense, because I was not refering to the instance (only the class!) but there must be a simpler way to do this, it just seems messy (even tho obviously logical). Is it common practice to do stuff like this? Is there a better way to organise my code? Sorry if I sound like a noob but I knew AS2 very well and with AS3 its all OOP and I am not used to the different types of problems that arise with it.
Thanks for the help,
Dan

BTW it extends Sprite cos its gona have visual functionality. I think I know about resource managment quite well but thanks for pointing it out.

Sirisian
July 21st, 2007, 05:22 PM
Yeah it's common practice. static class member function are the only other thing I can think of, but those are scoped to their package.