0

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

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 soon as mainState is called to start the 3rd line)?

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

mainState.prototype.myFunction() {}

I´ll get an error calling this and I can't explain.

Castro Roy
  • 7,623
  • 13
  • 63
  • 97
Faizy
  • 299
  • 2
  • 12
  • Maybe, because you have to write at least 'mainState.prototype...'. I think, it is recommned to use prototype with JavaScript "classes" – Guybrush May 09 '17 at 19:42
  • @Guybrush I meant 'mainState'. Edited it - thanks. – Faizy May 09 '17 at 19:58
  • You can also look here: http://stackoverflow.com/questions/43246989/the-value-of-this-inside-a-function/43247403#43247403. So it is a possibly duplicated question. – Guybrush May 09 '17 at 20:23
  • Is this question really a duplicate of the nested function question? It starts out sounding like it's about that, but then just seems to ask how to correctly define a prototype function. – Frank Modica May 09 '17 at 21:20

2 Answers2

-2

The mainState is an object literal. 'prototype' is a property of function object in javascript used for prototype inheritance. Javascript Prototype

vabii
  • 521
  • 6
  • 16
-2

One thing that always help me remember what the this will be is to look out for who is calling the function, check this snippet

var sayHi = function() { console.log(this.name) }

var yoda = { name: "Yoda", sayHi: sayHi }
var darthVader = { name: "Anakin Skywalker", sayHi: sayHi }

// the `this` here will be the yoda object
yoda.sayHi()
// the `this` here will be the darthVader object
darthVader.sayHi()

window.name = "Global name"
// here, since nothing was specified, the object is the global object, or the window on browsers, this the same as "window.sayHi()"
sayHi()