Reputation: 25
Is init()
function run once you instantiate it?
For example:
var circle:MovingCircle = new MovingCircle();
MovingCircle
class has an init()
function inside it.
Can someone enlighten me with init()
function?
Another question is:
What's the difference between MovieClip
, Shape
and Sprite
classes and when is it appropriate to use each?
Upvotes: 1
Views: 399
Reputation: 6209
Great answer by Marty above; but there is another; slightly more subtle reason to use the following class structure:
public class WobbleBobble {
// Constructor.
public function WobbleBobble() {
init();
}
private function init() : void {
// ...<snip>some complex initialisation logic</snip>....
}
}
You may be wondering why the the constructor calls the init() method; why not just put the complex initialisation logic block inside the constructor?
The answer is because the AVM doesn't JIT code placed inside a constructor; which results in it executing about 70% slower than code in other methods.
Upvotes: 4
Reputation: 39456
A constructor would be what you're thinking of when you say "run once your initialise it".
A constructor uses the same name as the class, eg:
public class Pants extends MovieClip
{
public function Pants()
{
trace('hello');
}
}
Now if we do:
var p:Pants = new Pants();
This code will be run also:
trace('hello');
An init()
function would be a custom function that people might use as an asynchronous constructor (ie a function you can call after you've defined other variables and such).
public class Pants extends MovieClip
{
public var str:String;
public function init():void
{
trace(str);
}
}
And then this would trace "some string":
var p:Pants = new Pants();
p.str = "some string";
p.init();
Personally, I use my own init()
function within a setter of a base class for my application objects, like this:
public class Pants extends MovieClip
{
private var _core:ApplicationCore;
private function _init():void
{
trace("application core is: " + _core);
}
public function set core(ac:ApplicationCore):void
{
_core = ac;
_init();
}
public function get core():ApplicationCore{ return _core; }
}
Then I can do this:
var appCore:ApplicationCore = new ApplicationCore();
var p:Pants = new Pants();
p.core = appCore;
Which will run my init()
function only after I've defined the application core.
As for your question of different types of classes - the goal is to use the most primitive form of a class possible.
If you just want a simple graphic that you can move around the screen, use Shape
. If you want to define more complex graphics, use Sprite
. If you want to be able to have timeline animation, use MovieClip
.
Basically, there's no need to be creating a MovieClip when all you want to do is create a blue square, but you'll need to use MovieClip or Sprite if you want to add other DisplayObjects to it.
Upvotes: 3