Jump to content

How is 'this' working here?


Faizy
 Share

Recommended Posts

I have a question about how the keyword 'this' works in the following context. Here´s a [tutorial][1] with the phaser framework and the code looks like the following(I simply merged it together for you):


  [1]: http://www.lessmilk.com/tutorial/flappy-bird-phaser-1
   

    var game = new Phaser.Game(400, 490);
    game.state.add('main', mainState); 
    game.state.start('main');
    
    var mainState = {
    preload: function() { 
    },

    create: function() { 
        this.bird = game.add.sprite(100, 245, 'bird');
    },

    update: function() {
    },
    };

In the create function there is a 'this'. I think I understand what this does, but this example proved me wrong. The this keyword - in this context- points to mainstate, right(just some information: the create function starts as soona s mainstate is called to start in the 3rd line)?

I can access the bird outside the mainstate object(via *mainstate.bird*), but why isnt it possible then to to define a prototype function like the following outside the game object?
    

mainState.prototype.myFunction() {}

I´ll get an error calling this and I cant explain. 

Link to comment
Share on other sites

mainState is just a plain object and doesn't have a prototype property. (This is actually the simpler way to write states.) Also the function syntax isn't quite right. You can use

mainState.myFunction = function () { /*…*/ };

 

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

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