mariogarranz Posted August 5, 2014 Share Posted August 5, 2014 I guess this may be a more generic Javascript question, but for me it is too related to the way I use Phaser Signal class, so I will ask in the Phaser forum. I often create local scope references to "this" inside prototyped functions, such as this:MyGame.Block.prototype.animate = function(){this.movementTween = this.game.add.tween(this.group.scale).to({x: 2, y:0.5},75,Phaser.Easing.Linear.None,true,0,false).to({x: 0.5, y:3},100,Phaser.Easing.Linear.None,true,0,false).to({x: 1.5, y:0.75},75,Phaser.Easing.Linear.None,true,0,false).to({x:1, y:1},150,Phaser.Easing.Linear.None,true,0,false).to({x:0,y:0},250,Phaser.Easing.Quadratic.In,true,100,false);var _this = this;this.movementTween._lastChild.onComplete.addOnce(function(){_this.movementFinished();_this.movementTween.pendingDelete = true;_this.movementTween = null;});};Then I have noticed my code is creating some weird and unexpected situations, and I'm starting to think that the variable "_this" may be shared for every "Block" object inside the game, so, one Block may be calling the "movementFinished" function of a different Block.Am I right about this, or is the above code OK? Link to comment Share on other sites More sharing options...
lewster32 Posted August 5, 2014 Share Posted August 5, 2014 The reference '_this' in your code above will only be accessible by anything inside the function in which it's defined, so in this case only animate and any functions defined inside animate. Phaser does actually provide a way to pass the context to signals, so you could rewrite the above like so:this.movementTween._lastChild.onComplete.addOnce(function(){ this.movementFinished(); this.movementTween.pendingDelete = true; this.movementTween = null;}, this);'this' will be the block object instance as you'd expect, and would not be shared. This is functionally equivalent to your code, just cleaner - so if you're having weird problems I think maybe it's elsewhere. Link to comment Share on other sites More sharing options...
Recommended Posts