AS3: why would "this" change what it's referring to when inside a function?

79 Views Asked by At

My code

for each(var enemy in RhythmGame.npcs) {
    if(this.hitTestObject(enemy)) {
        enemy.step(distance, axis, origin);
        enemy.damage(power);
    }
}

works fine until I put it in a function

separate();
function separate():void {
    for each(var enemy in RhythmGame.npcs) {
        if(this.hitTestObject(enemy)) {
            enemy.step(distance, axis, origin);
            enemy.damage(power);
        }
    }
}

and then I get the error

TypeError: Error #1006: hitTestObject is not a function.

I've found that this is referring to [object global] when it's in the function rather than the class instance it should be. Why would this happen? What don't I understand here about how scope works?

1

There are 1 best solutions below

1
On

I've found that this is referring to [object global] when it's in the function rather than the class instance it should be. Why would this happen? What don't I understand here about how scope works?

This is the expected behavior if your function is a closure and not a method. I'm guessing the code you posted is itself contained in a function or perhaps a class method, and might be called later as a callback or something.

From the docs on function scope:

The main difference between a function closure and a bound method is that the value of the this keyword in a bound method always refers to the instance to which it was originally attached, whereas in a function closure the value of the this keyword can change.