繁体   English   中英

TypeError:undefined不是函数(Phaser JS)

[英]TypeError: undefined is not a function (Phaser JS)

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

我正在调用其他函数,并且运行良好,所以我听不懂。 我试图更改名称,但一无所获。

我认为我正在使用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';
    }
}

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

是问题。 在JS,该值this函数内取决于函数是如何被调用。 .collide() collisionBlocs的引用传递给.collide()方法,当它调用它时,它将无法正确设置this ,因此this.bounce将是undefined

你需要给力的值this是正确的。 最简单的方法是使用.bind()

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

较旧的浏览器(IE <= 8)不支持.bind()方法 ,但是如果需要支持这些浏览器,可以使用polyfill

MDN有更多的信息, 如何this工作在JavaScript中

而结合this会更容易使用callbackContext参数collide ,为您提供。 它专门针对此问题而添加。 这是方法签名:

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

您没有使用processCallback因此可以processCallback传递null ,但是您确实需要上下文。 这是将在其中调用回调的上下文(尝试this开始)。

暂无
暂无

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

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