Jump to content

Inheritance without setting proto


buttonsrtoys
 Share

Recommended Posts

I'm getting up to speed on it JS inheritance and Phaser and came across an interesting blog advocating not explicitly setting prototype (aside from within Object.create). The blog is http://davidwalsh.name/javascript-objects-deconstruction and below is an example of the approach.

var Foo = {    init: function(who) {        this.me = who;    },    identify: function() {        return "I am " + this.me;    }};var Bar = Object.create(Foo);Bar.speak = function() {    alert("Hello, " + this.identify() + ".");};var b1 = Object.create(Bar);b1.init("b1");var b2 = Object.create(Bar);b2.init("b2");b1.speak(); // alerts: "Hello, I am b1."b2.speak(); // alerts: "Hello, I am b2."

I trying to use this approach to created a custom Sprite object: 

var sprite = game.add.sprite(game.world.randomX, game.world.randomY, 'myTexture');var customSprite = Object.create (sprite);customSprite.sayHello = function () {    console.log('hello from customSprite');};

The above works except 'sprite' is added to the game, rather than 'customSprite' because I don't know how create a sprite without using a function call that also adds it to the game. Is there a Phaser call that creates a sprite without adding it to the game? And another that would add customSprite? I don't need to override any of sprite's methods, such as 'update'. I just want to add a couple methods to 'customSprite'.

Link to comment
Share on other sites

Your solution didn't work for me without assigning the prototype property. Below is code I used to test it. 

<!DOCTYPE html><html><head>    <title>inheritance example</title>    <script type="text/javascript" src="js/phaser.min.js"></script></head><body>    <script type="text/javascript">            var CustomSprite = function(game, x, y) {                Phaser.Sprite.call(this, game, x, y, 'bug');                this.anchor.set(0.5);            }            // had to add the line below, which is what I was trying to avoid            CustomSprite.prototype = Object.create(Phaser.Sprite.prototype);            var game = new Phaser.Game(800, 600, Phaser.AUTO, '', {                preload: preload,                create: create            });            function preload() {                game.load.image('bug', 'assets/ladybug_big.png');            }            function create() {                var player = new CustomSprite(game, this.world.centerX, this.world.centerY);                game.add.existing(player);            }    </script></body></html>
Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...