我正在创建一个画布游戏,下面的代码显示了全局变量和init函数。根据我的理解,创建全局变量是错误的做法,可能会导致与其他文件的冲突。
有人能给我举个例子,说明如何用生命来改进这段代码吗?
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();
}发布于 2016-12-05 11:40:00
iife (立即调用函数表达式)实际上是一种非常简单的避免全局的技术。
(function() {
//your code
})();但是,您应该考虑使用诸如ES6模块、CommonJS (节点的module.exports/require)或AMD模块,因为这些模块都有自己的范围,因此没有必要使用iife。
https://stackoverflow.com/questions/40973415
复制相似问题