Javascript Uncaught TypeError: undefined is not a function
I am trying to make a simple game using the Phaser engine but I still get 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 playerJump function. All the variables you see in the sample are correctly defined and working. When I call the "playerJump" function from "updatePlayer" I get no error. However, if I try to call it from "spacePressed", I get "undefined is not a function exception.
I am using Phaser engine and all my code is in one file, if that matters. The "spacePressed" function is called from the callback function when a key is pressed. "UpdatePlayer" on is called from the main game update loop.
Do you have any idea why this might be happening? Why does it work when I call it one function but not another? We wish to provide more code and details if needed.
source to share
When you use a method of an object as an event handler or callback function, this one will no longer refer to the object.
The easiest way to solve this problem:
var mainState = { ... };
element.addEventListener(type, mainState.spacePressed.bind(mainState), false);
This method may not be supported with every browser / version, so you can use this:
var mainState = { ... };
element.addEventListener(type, function() {
mainState.spacePressed.call(mainState);
}, false);
source to share
I am assuming you have created an input handler to determine if a space is pressed.
This is the code for detecting a mouse click on a button (for example). Just pass in "this" to the second parameter so that the callback gets the mainState context so you can call it later this.playerJump()
.
spaceButton.events.onInputDown.add(this.spacePressed,this)
will solve your problem when you call this.playerJump()
inside the method spacePressed()
.
source to share