This problem has occurred to me again in the past and I used global variables but I’d like to know what other way there is to deal with it.
The code is from an html5 canvas tutorial I’m playing with at the moment.
var x = 150;
var y = 150;
var dx = 2;
var dy = 4;
var ctx;
function init() {
ctx = $('#canvas')[0].getContext("2d");
return setInterval(draw, 10);
}
function draw() {
ctx.clearRect(0,0,300,300);
ctx.beginPath();
ctx.arc(x, y, 10, 0, Math.PI*2, true);
ctx.closePath();
ctx.fill();
x += dx;
y += dy;
}
init();
What can I do to avoid using global variables?
You could use the module pattern – it’s a neat way of providing encapsulation:
Read more about it at http://addyosmani.com/largescalejavascript/#modpattern.