Jump to content

Phaser Code Explanation


seand88
 Share

Recommended Posts

I have a question about the usage of prototypes and logic in phaser. 

I have this code.... 

Runner.Map = function(game) {};//initialize the map variablesRunner.Map.startX = 0;Runner.Map.newFunction = function(){//this does not exist when logging!!}//prototype objectRunner.Map.prototype = {create: function(){console.log(this);

The Runner.Map.newFunction does not show up in the "this" object when i read the output of console.log. The Primitive variable Runner.Map.startX does show up.

Why is this? 

 

I can fix the issue by placing the function within the objects prototype by adding Runner.Map.prototype.newFunction, but why should I have to do this? As far as I understand prototypes should only be used when I have an object that is going to be created with multiple instances. This object is only going to be created once so I figure I should not place the function in the prototype. 

 

Does Phaser not allow functions to be added to Game States except for in the prototype but allows primitive types? Seems to be that way but would like some more explanation

 

Thanks!

 

 
Link to comment
Share on other sites

You're confusing the object that gets assigned to "this" and your constructor. Runner.Map is your constructor function and is a first class object. That means you can assign properties to it (like "Runner.Map.newFunction"). But assigning properties to that function don't make them show up on the instances that are created for you when you call that function with the new operator (e.g. "new Runner.Map();").

 

You're right, there is only going to be one state. You don't have to create a function and assign to its prototype to achieve what you want, you could make an object literal as well:

Runner.Map = {  newFunction: function() {},  create: function() {}};
Link to comment
Share on other sites

I understand what you are saying now that I look at it from that perspective. 

I am still confused as to why 

Runner.Map.startX = 0;

Shows up when "this" is logged in the console.

 

If what you are saying is true that assigning properties to that function don't make them show up on instances, then why does the instance have the property startX ?

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

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