LoginSignup
3
3

More than 5 years have passed since last update.

requestAnimationFrame内でthisが変わるの知らないよぉ

Posted at

本日ハマったこと。

class World
    update:->
        requestAnimationFrame @update
        @render

    render:->
        # hoge

これで動くと思ったけど、全然動かない。

CoffeeScript内の@もといthisの扱いにはマジで注意が必要ですね。

class World
    update:->
        requestAnimationFrame arguments.callee
        @render

    render:->
        # hoge

こうしてみた。
うごかない。

ちなみに、arguments.callee で呼び出している関数は、グローバルオブジェクトになるのかな。怖い怖い。一回目は通るけど、二回目は通らないってそういうことなのか?。

でも、一個目のやつが動かないのは説明がつかない。

うーむおかしい。

->と=>の違い

class World
    update:=>
        requestAnimationFrame @update
        @render

    render:=>
        # hoge

結果的に、こうすることで解決しました。

どうやら、requestAnimationFrameはグローバルオブジェクトなので、引数の関数を呼ばれると、内部のthisはwindowを指すことになってしまう模様。

つまりは、Worldクラスのthisをbindしてあげないと、ちゃんと動かないっぽいです。

coffeeScriptの=>はthisを関数にBindしてくれて、ちゃんとしたWorldのthisを使えるようにしてくれるやつです。

これで、->=>の使い分けられる人類に一歩近づきました。

ちかれた。

3
3
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3