Jump to content

Variable scope inside module.


momenimum
 Share

Recommended Posts

Hi I have a very basic question.  If I want variables to remain scoped to its module what is the best way to do it?  So the below example I want every class created inside the module to be able to see "score".  Right now I use game.score, I can also use global scope with window.  But is there a better way?

game.module(
    'game.main'
)
.body(function() {

game.addAsset('screen.png');

game.score = 0; //I want everything in the module to see this
game.hiscore = 0; //I want everything in the module to see this

game.createClass('PreLoader', 'Loader', { ... //This class sees game.score 

game.createScene('Title', { ... //This class sees game.score 

game.createScene('Main', { .. //This class sees game.score 
Link to comment
Share on other sites

You can just do it like this:

game.module(
    'game.main'
)
.body(function() {
    
var score = 0;

game.createScene('Main', {
    init: function() {
        console.log(score); // 0
    }
});

});

Because the "score" variable is defined with var keyword inside the module, it won't be visible to any other modules, but will be visible to all classes inside that module.

It's not good idea to create variables into root of game object, because you might overwrite something important.

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
 Share

  • Recently Browsing   0 members

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