Subclassing a Phaser.Sprite
- 1 Min. Read.
Inheritance in Javascript can be a bit confusing if you come from a class-based language (C++ for example).
When it comes to inheritance, JavaScript only has one construct: objects. Each object has an internal link to another object called its prototype. That prototype object has a prototype of its own, and so on until an object is reached withnull
as its prototype.null
, by definition, has no prototype, and acts as the final link in this prototype chain. Source: developer.mozilla.org
When I was developing a game in the PhaserJS framework, I found myself in a position where I wanted to create a subclass of Phaser.Sprite and came up with the following template.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
var MySprite = (function(){ // Constructor for the custom sprite function MySprite(game, x, y) { // Call the super class Phaser.Sprite.call(this, game, x, y, 'asset'); } // Assign the prototype of MySprite to the Phaser.Sprite.prototype MySprite.prototype = Object.create(Phaser.Sprite.prototype); // Override the constructor MySprite.prototype.constructor = MySprite; // Return the MySprite return MySprite; })(); |
Now when we want to create an instance of MySprite and add it to the stage, we just do the following.
1 2 |
var sprite = new MySprite(phaserGame, 0, 0); phaserGame.add.existing(sprite); |
And there we have it! A template for subclassing Phaser.Sprite!