简体   繁体   中英

Javascript Uncaught TypeError: undefined is not a function

I am trying to make a simple game using the Phaser engine, but I keep getting the above error.

var mainState = {
...
playerJump: function(){
    yVelocity = -jumpPower;
},

spacePressed: function(){
    if(started)
    {
        return;
    }
    started = true;
    this.playerJump();
},      
...
updatePlayer: function(){
    if(player.body.x < game.world.centerX)
    {
        player.body.x += xVelocity;
    }

    player.body.y += yVelocity;
    yVelocity += gravity;

    if(player.body.y + player.body.height > floor)
    {
        this.playerJump();
    }
},

...}

As you can see I have defined the function playerJump. All variables you see in the sample are properly defined and working. When I call the function "playerJump" from "updatePlayer" I get no error. However, if I try to call it from "spacePressed" I get the "undefined is not a function exception.

The engine I am using is Phaser and all of my code is in one file, if that makes any difference. The function "spacePressed" is invoked from a callback function when the key is pressed. The "updatePlayer" on is called from the main Update loop of the game.

Do you have any ideas why this might be happening? Why am does it work when I call it from one function but not from the other? Happy to provide more code and details if necessary.

When you use a object method as an event handler or a callback function, this will no longer refer to the object.

The simplest way to solve this:

var mainState = { ... };
element.addEventListener(type, mainState.spacePressed.bind(mainState), false);

This method might not be supported with every browser / version so you can use this instead:

var mainState = { ... };
element.addEventListener(type, function() {
    mainState.spacePressed.call(mainState);
}, false);

I assume you have created an input handler to detect if space is pressed.

This is the code to detect a mouse click on a button (for example). Just pass in "this" to the second parameter so that the callback will receive the mainState context, so that you can invoke this.playerJump() later on.

spaceButton.events.onInputDown.add(this.spacePressed,this)

will solve your problem when you call this.playerJump() inside the spacePressed() method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM