TypeError:undefined不是函数(Phaser JS) [英] TypeError: undefined is not a function (Phaser JS)

查看:108
本文介绍了TypeError:undefined不是函数(Phaser JS)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,我只是尝试在一个类中执行一个方法,但是它没有用. 我收到未捕获的TypeError:未定义不是函数"错误.

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.

我认为我使用的Phaser有问题,但我不知道...

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

推荐答案

实际上,collisionBlocs()是移相器碰撞事件的回调函数:game.physics.arcade.collide(this.sprite, blocs, this.collisionBlocs);也许是问题所在"

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

那是 的问题.在JS中,函数中this的值取决于函数的调用方式.您将对collisionBlocs的引用传递给.collide()方法,当它调用它时,它将不会正确设置this,因此this.bounce将是undefined.

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.

您需要强制this的值正确.最简单的方法是使用.bind():

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

.bind()方法,但是存在

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有关 this的工作方式的详细信息在JavaScript中.

MDN has more information on how this works in JavaScript.

这篇关于TypeError:undefined不是函数(Phaser JS)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆