TypeError: undefined is not a function (Phaser JS)

2019-09-20 06:36发布

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';
    }
}

2条回答
祖国的老花朵
2楼-- · 2019-09-20 07:10

"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.

查看更多
放我归山
3楼-- · 2019-09-20 07:21

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).

查看更多
登录 后发表回答