2016-12-05 12 views
0

私はキャンバスゲームを作成しています。下のコードはグローバル変数とinit関数を示しています。グローバル変数を作成する私の理解から、悪い習慣であり、他のファイルとの衝突につながる可能性があります。IIFEを使用してキャンバスコードを改善する

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(); 
} 
+0

コードレビューを依頼しているので、この質問を閉鎖する投票があります – Alnitak

答えて

2

iife(Immediately Invoked Function Expression)は、実際にグローバルを避けるための非常に簡単な手法です。これらはすべて、独自のスコープを持ち、生命維持のが不要になりますよう、あなたが、このようES6 modules、CommonJS(ノードのmodule.exports/require)またはAMDモジュールなどのモジュールを使用することを検討すべきであるしかし

(function() { 

    //your code 

})(); 

+0

ありがとうございましたNexus、私はここで答えを見つけましたhttp://stackoverflow.com/questions/8228281/what-is-the-function -construct-in-javascript – stckpete

関連する問題