AS3:为什么“this”会在函数内部改变它指的是什么?
我的代码AS3:为什么“this”会在函数内部改变它指的是什么?
for each(var enemy in RhythmGame.npcs) {
if(this.hitTestObject(enemy)) {
enemy.step(distance, axis, origin);
enemy.damage(power);
}
}
正常工作,直到我把它放在一个函数
separate();
function separate():void {
for each(var enemy in RhythmGame.npcs) {
if(this.hitTestObject(enemy)) {
enemy.step(distance, axis, origin);
enemy.damage(power);
}
}
}
,然后我得到的错误
TypeError: Error #1006: hitTestObject is not a function.
我发现this
指的是[object global]
当它在函数中而不是类实例时它应该是。为什么会发生?我在这里不了解范围如何工作?
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?
这是预期的行为,如果你的函数是一个关闭而不是方法。我猜你所发布的代码本身包含在一个函数或一个类方法中,可能稍后会被称为回调函数或其他东西。
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 thethis
keyword can change.
你猜对了。它在另一个函数中并被称为TimerEvent。 –
诊断它:**跟踪(本); ** **跟踪(typeof运算(本)); ** **跟踪(的getQualifiedClassName(本)); ** * * trace(这是DisplayObject); **两种情况并比较(并更新您的问题)。 – Organis
好的电话。它确实失去了“这是什么”的踪迹。 –
您是否在其他函数中定义了此函数? – Organis