Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/375.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript未捕获类型错误:未定义不是函数_Javascript_Exception_Phaser Framework - Fatal编程技术网

Javascript未捕获类型错误:未定义不是函数

Javascript未捕获类型错误:未定义不是函数,javascript,exception,phaser-framework,Javascript,Exception,Phaser Framework,我试图用相位器引擎做一个简单的游戏,但是我一直得到上面的错误 var mainState = { ... playerJump: function(){ yVelocity = -jumpPower; }, spacePressed: function(){ if(started) { return; } started = true; this.playerJump(); }, ... updatePlayer: f

我试图用相位器引擎做一个简单的游戏,但是我一直得到上面的错误

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();
    }
},

...}
var-mainState={
...
playerJump:function(){
yVelocity=-jumpPower;
},
spacePressed:function(){
如果(启动)
{
返回;
}
开始=真;
这个。playerJump();
},      
...
updatePlayer:function(){
if(player.body.xfloor)
{
这个。playerJump();
}
},
...}
如您所见,我已经定义了函数playerJump。您在示例中看到的所有变量都已正确定义并正常工作。当我从“updatePlayer”调用函数“playerJump”时,没有得到任何错误。然而,如果我尝试从“spacePressed”调用它,我会得到“undefined不是函数异常”

我使用的引擎是Phaser,我所有的代码都在一个文件中,如果这有什么区别的话。当按下键时,函数“spacePressed”从回调函数调用。上的“updatePlayer”是从游戏的主更新循环调用的


你知道为什么会发生这种情况吗?为什么当我从一个函数调用它而不是从另一个函数调用它时,它会工作?如果需要,很乐意提供更多的代码和细节。

当你使用对象方法作为事件处理程序或回调函数时, 将不再引用对象

解决此问题的最简单方法是:

var mainState = { ... };
element.addEventListener(type, mainState.spacePressed.bind(mainState), false);
并非每个浏览器/版本都支持此方法,因此您可以改用此方法:

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

我假设您已经创建了一个输入处理程序来检测是否按下了空格

这是检测鼠标单击按钮(例如)的代码。只需将“This”传递给第二个参数,这样回调将接收主状态上下文,以便稍后可以调用
This.playerJump()

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


当您在
spacePressed()
方法中调用
this.playerJump()
时,将解决您的问题。

如果您在中重现您的问题,那么我们也许可以帮助您。您的“spacePressed”“函数可能是从事件处理程序调用的,
this
的值不是您所认为的值。是的,my spacePressed实际上是从事件处理程序调用的。在这种情况下,我如何访问该函数?请尝试mainState.updatePlayer(),如果对按钮调用了updatePlayer函数,请单击“this”对象引用已单击的按钮