PDA

View Full Version : Simple Instatiate Question


Whittler
03-16-2011, 08:24 PM
Regarding these declarations:

var songList_XML:XML;
var xmlLoader:URLLoader = new URLLoader();

I'm working off of the ASCS5 CIB book and ran across these statements an other like this. Why is it (or when is it) that when putting a class into a var with nothing in it, you have to preceded it with "new?" I think the term is called instantiate it? I'm having a problem understanding this logic. They're both new. Why not:

var songList_XML: new = XML();
var xmlLoader:URLLoader = new URLLoader();

Is it because of the type of classes they are? If so, how do I know which ones to instantiate with the word "new" and which ones not to use "new."

Thanks in advance,

Newb
:confused:

Rhuno
03-17-2011, 12:36 PM
You are correct; using the keyword "new" creates an instance of the object (hence the term instantiate). :)

You can actually use the new keyword with any class, it just depends on if you need the object right away or not. For instance, in your example, the xml variable is declared, but not yet instantiated. The URLLoader is both declared and instantiated. I would bet that later on in code there is something that looks like this:


songList_XML = new XML(xmlLoader.data);


So what's the difference between declaring a variable and instantiating it? Well, you can do a trace to see that.


var songList_XML:XML;
var xmlLoader:URLLoader = new URLLoader();

trace(songList_XML);
trace(xmlLoader);


In the above code, songList_XML will trace out as "null" because it does not have a value. The xmlLoader DOES have a value because it was instantiated using the new keyword.

It might be a little fuzzy at first, but you'll get the hang of it.

Whittler
03-17-2011, 06:46 PM
It makes perfect sense now.

Thanks.
;)