TypeError: undefined is not a function (Phaser JS)

与世无争的帅哥 提交于 2019-12-13 08:19:48

问题


Hi everybody i'm just trying executing a method inside a class and it's not working. I got an "Uncaught TypeError: undefined is not a function" error.

I'm calling others functions and it's working well so I don't understand. I've tried to change the name and nothing.

I think that there is a problem with Phaser that I'm using but I've no idea...

Bomb.prototype.collisionBlocs = function() {
    if (!this.hasBounced) {
        this.bounce();
        this.hasBounced = true;
    }
}

Bomb.prototype.bounce = function() {       
    if (this.direction == 'UP') {
        this.direction = 'DOWN';
    }
    else if (this.direction == 'RIGHT') {
        this.direction = 'LEFT';
    }
    else if (this.direction == 'DOWN') {
        this.direction = 'UP';
    }
    else if (this.direction == 'LEFT') {
        this.direction = 'RIGHT';
    }
}

回答1:


"In fact, collisionBlocs() is a callback function from a phaser collision events : game.physics.arcade.collide(this.sprite, blocs, this.collisionBlocs); Maybe that's the problem"

That will be the problem. In JS, the value of this within a function depends on how a function is called. You pass a reference to collisionBlocs to the .collide() method and when it calls it it won't be setting this correctly so then this.bounce will be undefined.

You need to force the value of this to be correct. The easiest way to do that is with .bind():

game.physics.arcade.collide(this.sprite, blocs, this.collisionBlocs.bind(this));

The .bind() method is not supported in older browsers (IE <=8), but there is a polyfill you can use if you need to support those browsers.

MDN has more information on how this works in JavaScript.




回答2:


Rather than binding this it would be easier to use the callbackContext parameter that collide offers you. It was added for specifically this issue. Here's the method signature:

collide: function (object1, object2, collideCallback, processCallback, callbackContext)

You're not using processCallback so you can pass null for that, but you do need the context. This is the context in which the callback will be invoked (try this to start with).



来源:https://stackoverflow.com/questions/27760125/typeerror-undefined-is-not-a-function-phaser-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!