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';
}
}
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 tocollisionBlocs
to the.collide()
method and when it calls it it won't be settingthis
correctly so thenthis.bounce
will beundefined
.You need to force the value of
this
to be correct. The easiest way to do that is with.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 has more information on how
this
works in JavaScript.Rather than binding
this
it would be easier to use thecallbackContext
parameter thatcollide
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 passnull
for that, but you do need the context. This is the context in which the callback will be invoked (trythis
to start with).