私はキャンバスゲームを作成しています。下のコードはグローバル変数と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();
}
コードレビューを依頼しているので、この質問を閉鎖する投票があります – Alnitak