undefined is not a function when evaluating 'this.batman()'

364 Views Asked by At

I'm trying to use coffeescript with box2dweb to create a simple game. Setting up the physics works fine and updates fine but when it comes to trying to call my own functions in the update loop I get this error 'undefined is not a function (evaluating this.batman())' (batman being the function name). I'm compiling to javascript before running it. This is my first time using coffeescript so I may be doing something stupid.

Here's my code:

root = exports ? this
root.world = null

class Game
    class Game
    canvasHeight: 450
    canvasWidth: 800
    canvas: null
    drawingContext: null

    constructor: ->
        @createCanvas()
        @resizeCanvas()
        @createDrawingContext()
        @initPhysics()

    createCanvas: ->
        @canvas = document.createElement 'canvas'
        document.body.appendChild @canvas

    resizeCanvas: ->
        @canvas.height = @canvasHeight
        @canvas.width = @canvasWidth

    createDrawingContext: ->
        @drawingContext = @canvas.getContext '2d'

    initPhysics: ->
        #physics setup removed for brevity

        window.setInterval(@update, 1000 / 60)


    batman: ->
        alert "whatever"

    update: ->
        root.world.Step(1 / 60,  10, 10)
        root.world.DrawDebugData()
        root.world.ClearForces()
        @batman()


    window.Game = Game
1

There are 1 best solutions below

4
On BEST ANSWER

In initPhysics, you need to bind @update to this:

window.setInterval(@update.bind(this), 1000 / 60)

because otherwise the this context is lost when update is called.