0

I'm creating a Canvas game, the code below shows the global variables and the init function. From my understanding creating global variables is bad practice and may lead to clashes with other files.

Can someone give me an example of how to improve this code using IIFE?

    canvasEntities = document.getElementById("canvasEntities"), // foreground canvas
    ctxEntities = canvasEntities.getContext("2d"),

    canvasWidth = 400,
    canvasHeight = 400,

    player1 = new Player(),   
    enemies = [],
    numEnemies = 5,
    obstacles = [],
    isPlaying = false,
    requestAnimFrame =  window.requestAnimationFrame ||   // Controls timing and update of game
                        window.webkitRequestAnimationFrame ||
                        window.mozRequestAnimationFrame ||
                        window.oRequestAnimationFrame ||
                        window.msRequestAnimationFrame ||
                        function(callback) {                // Older broswers
                            window.setTimeout(callback, 1000 / 60);
                        },


imgSprite = new Image();   // create sprite object
imgSprite.src = "images/sprite.png";
imgSprite.addEventListener("load", init, false);  

// event listener looks at image sprite waits for it to load, then calls init 



function init() {                                                                                        
    defineObstacles();                                                            
    initEnemies();
    begin();
}
stckpete
  • 571
  • 1
  • 4
  • 13

1 Answers1

2

An iife (Immediately Invoked Function Expression) is a very simple technique for avoiding globals indeed.

(function() {

  //your code

})();

However you should consider using modules such as ES6 modules, CommonJS (node's module.exports/require) or AMD modules, as these will all have their own scope and makes iife's unnecessary.

Robin-Hoodie
  • 4,886
  • 4
  • 30
  • 63
  • Thanks Nexus, I found the answer here http://stackoverflow.com/questions/8228281/what-is-the-function-construct-in-javascript – stckpete Dec 05 '16 at 11:50