2017-09-14 128 views
1

我的代碼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]當它在函數中而不是類實例時它應該是。爲什麼會發生?我在這裏不瞭解範圍如何工作?

+0

診斷它:**跟蹤(本); ** **跟蹤(typeof運算(本)); ** **跟蹤(的getQualifiedClassName(本)); ** * * trace(這是DisplayObject); **兩種情況並比較(並更新您的問題)。 – Organis

+0

好的電話。它確實失去了「這是什麼」的蹤跡。 –

+0

您是否在其他函數中定義了此函數? – Organis

回答

2

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 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.

+0

你猜對了。它在另一個函數中並被稱爲TimerEvent。 –

相關問題