polo Posted June 12, 2014 Share Posted June 12, 2014 I try to implement a input event handler from an class inherited of Sprite class. See below Rts.Unit = function Unit(game, x, y) { Phaser.Sprite.call(this, game, x, y, 'player'); this.inputEnabled = true; this.selected = false; this.events.onInputDown.add(this.select); return this;}; Rts.Unit.prototype = Object.create(Phaser.Sprite.prototype);Rts.Unit.prototype.constructor = Rts.Unit; Rts.Unit.prototype.dummy = function() { console.log("dummy");} Rts.Unit.prototype.select = function() { this.selected = true; this.dummy();}; but it's doesnt work and raise error"Uncaught TypeError: undefined is not a function" My game is manage by state.Regards Link to comment Share on other sites More sharing options...
ragnarok Posted June 12, 2014 Share Posted June 12, 2014 Most often, when I get such errors, it's because 'this' is not what I expect it to be. The development tools should tell you which line the error occurs in. Put a "console.log(this);" in the line before and restart. The next time the error comes up, take a look what 'this' really is and if it has the method you want. For if 'this' is your gamestate-object and you expect it to be 'game', try "this.game" instead. Link to comment Share on other sites More sharing options...
polo Posted June 13, 2014 Author Share Posted June 13, 2014 Thanks , that's true "this" is not what i expected in this context, i don't understand why in the event context i can't use a self reference to an object function. Why the "event" works in game -state context ? Link to comment Share on other sites More sharing options...
lewster32 Posted June 13, 2014 Share Posted June 13, 2014 You can pass the context you need to the signal, like so:this.events.onInputDown.add(this.select, this);The second parameter is the context you want it to run in. Link to comment Share on other sites More sharing options...
ragnarok Posted June 13, 2014 Share Posted June 13, 2014 Thanks , that's true "this" is not what i expected in this context, i don't understand why in the event context i can't use a self reference to an object function. Why the "event" works in game -state context ? You can (as Lewester pointed out), it's just, that 'this' act's really strange or someone coming from other langages. These links might be of interest: http://www.quirksmode.org/js/this.htmlhttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this Link to comment Share on other sites More sharing options...
polo Posted June 13, 2014 Author Share Posted June 13, 2014 Thanks for all your support, it works like lewster32 explain. Link to comment Share on other sites More sharing options...
Recommended Posts