I'm used to seeing the Loader class used like this:
var loader:Loader = new Loader();
loader.loadBytes(myByteArray);
addChild(loader);
But then I came across some code where it's all done on one line:
Loader(addChild(new Loader())).loadBytes(myByteArray);
What's the difference between the two? Is one way better than the other? Can someone explain what exactly is going on in the second version?
There is barely any difference, and the first version is "better" because it's actually readable.
To break it down:
Loader(addChild(new Loader())).loadBytes(myByteArray);
We cast something as an Object of the type Loader
: Loader(...)
Then we add a DisplayObject to the current displaylist with addChild
, which will return the DisplayObject we have added (so that we actually have something that we can cast to something else).
The DisplayObject in question is a Loader
Object, and we create a new one for this.
So, Loader(addChild(new Loader()))
creates a new Loader object and adds it to the displaylist. But this is still kind of useless, because a Loader needs to, well, load something, right? This is the reason why we cast the whole DisplayObject into a Loader
in the first place, so that we can use its methods, such as loadBytes(bytearray)
. If you wouldn't put the whole thing into a Loader(...)
cast, you wouldn't have access to these methods, because addChild will only return an object of the DisplayObject type, and not Loader.
To sum it up, this has no effect on performance whatsoever, it's just a shorter writing style for the same goal. If you're the only one who will see this code in your projects, it's fine. If not, consider that other people should be able to read the code as well, without having to break it down step for step.