Copy link to clipboard
Copied
Hello,
I found this code for a preloader. The part I never get is the usage of the this keyword.
stop();
this.addEventListener(Event.ENTER_FRAME, loading);
function loading(e:Event):void{
var total:Number = this.stage.loaderInfo.bytesTotal;
var loaded:Number = this.stage.loaderInfo.bytesLoaded;
bar_mc.scaleX = loaded/total;
loader_txt.text = Math.floor((loaded/total)*100)+ "%";
if (total == loaded){
play();
this.removeEventListener(Event.ENTER_FRAME, loading);
}
}
Where ir says:
var total:Number = this.stage.loaderInfo.bytesTotal;
Is it suggesting this stage ? Meaning is there some other stage? Is the this keyword even needed?
Thanks,
Jim
Copy link to clipboard
Copied
It's usually not needed.
Copy link to clipboard
Copied
AttaBoy is right, this is rarely needed anymore with AS3. The only time I have used it recently is when I need to use bracket notation to be able to iterate a sequence like:
this["image" + i].x = ...
That being said, you can simply remove this from your code sample and it'll be fine. And to be clear - this refers to the current timeline.. but you're 'in' the current timeline... so no need for 'this'.
Copy link to clipboard
Copied
When you write a class this can be useful if you want to make a function parameter available to the entire class. Something like below where this.w=w makes the w var available to the entire class.
package{
import flash.display.Sprite;
public class ClassName extends Sprite {
private var w:Number;
private var h:Number;
//- CONSTRUCTOR --------------------------------------
public function ClassName(w:Number, h:Number) {
this.w=w;
this.h=h;
}
//- PUBLIC METHODS ------------------------------------
public function myFunction():void {
trace(w, h);
}
}
}
Copy link to clipboard
Copied
This is still not needed - it's easier to use $:
public function ClassName($w:Number, $h:Number) {
w = $w;
h = $h;
}