mattbrand Posted November 7, 2016 Share Posted November 7, 2016 I don't know how to call a class member function from a button declared within the same class. Here is my code: class Player { constructor() { this.sprite = game.add.sprite(0, 0, "player"); this.sprite.scale.setTo(scale.x, scale.y); this.sprite.x = gameWidth / 2; this.sprite.y = game.world.height - (this.sprite.height / 2); game.physics.p2.enable(this.sprite, false); this.sprite.body.setCircle(45 * scale.x); this.sprite.body.setCollisionGroup(playerCollisionGroup); this.sprite.body.collides(bubbleCollisionGroup, playerHitBubble, this); this.sprite.body.static = true; this.button = game.add.button(0, 0, "player", onClick); this.button.scale.setTo(scale.x, scale.y); this.button.anchor.setTo(0.5, 0.5); this.button.x = this.sprite.x; this.button.y = this.sprite.y; this.shootingMode = ShootingMode.SPLIT; } onClick() { console.log(this); if (this.shootingMode == ShootingMode.SPLIT) { this.shootingMode = ShootingMode.BOUNCE; this.sprite.tint = 0x000000; } else { this.shootingMode = ShootingMode.SPLIT; this.sprite.tint = 0xffffff; } } } As it is, I get the error message that onClick is not defined. But if i call it as "this.onClick", then "this" in the onClick function is the button, not the class instance. Any ideas? Link to comment Share on other sites More sharing options...
Théo Sabattié Posted November 7, 2016 Share Posted November 7, 2016 this.button = game.add.button(0, 0, "player", this.onClick.bind(this)); EventDispatcher bind object as this on callback listener, if you bind your own this, you don't have problem drhayes 1 Link to comment Share on other sites More sharing options...
mattstyles Posted November 8, 2016 Share Posted November 8, 2016 Do a bit of research on scoping in JS, then move on to what `.bind`, `.call` and `.apply` do. It can get tricky, don't necessarily expect to pick it up entirely at first, but work to understand it fully, it'll save you a load of headaches (like this one). Link to comment Share on other sites More sharing options...
mattbrand Posted November 8, 2016 Author Share Posted November 8, 2016 Thank you both! Link to comment Share on other sites More sharing options...
Recommended Posts