Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
305 views
in Technique[技术] by (71.8m points)

javascript - TypeError: undefined is not a function (Phaser JS)

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';
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...