简体   繁体   English

TypeError:undefined不是函数(Phaser JS)

[英]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. 我收到“未捕获的TypeError:未定义不是函数”错误。

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... 我认为我正在使用Phaser出现问题,但我不知道...

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

"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" “实际上, collisionBlocs()是移相器碰撞事件的回调函数: game.physics.arcade.collide(this.sprite, blocs, this.collisionBlocs);也许就是问题所在”

That will be the problem. 是问题。 In JS, the value of this within a function depends on how a function is called. 在JS,该值this函数内取决于函数是如何被调用。 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 . .collide() collisionBlocs的引用传递给.collide()方法,当它调用它时,它将无法正确设置this ,因此this.bounce将是undefined

You need to force the value of this to be correct. 你需要给力的值this是正确的。 The easiest way to do that is with .bind() : 最简单的方法是使用.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. 较旧的浏览器(IE <= 8)不支持.bind()方法 ,但是如果需要支持这些浏览器,可以使用polyfill

MDN has more information on how this works in JavaScript . MDN有更多的信息, 如何this工作在JavaScript中

Rather than binding this it would be easier to use the callbackContext parameter that collide offers you. 而结合this会更容易使用callbackContext参数collide ,为您提供。 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. 您没有使用processCallback因此可以processCallback传递null ,但是您确实需要上下文。 This is the context in which the callback will be invoked (try this to start with). 这是将在其中调用回调的上下文(尝试this开始)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM