Was talking with a coworker explaining what a bit of javascript syntax was doing, and reminded me of a good explanation of what a closure is in Javascript.
The short version of it is that:
A closure, enCLOSES all the variables – allowing you to access them from anywhere within that… enCLOSURE
This is because javascript only has one kind of scope, function scope.
Everything inside of a function has access to the created by the parent function.
So you can have something like this
var CanvasDemo = function() {
return this;
};
// On Ready Callback
CanvasDemo.onReady = function(e)
{
this.canvas = this.createCanvas();
this.canvasContext = this.canvas.getContext('2d');
this.canvasContext.fillRect(100, 100, 50, 50);
this.loadTruck();
// Start rendering loop
var that = this;
this.loopInterval = setInterval(function() {
console.log(this); // 'this' - refers to document window
console.log(that); // 'that' - refers to 'CanvasDemo' instance
this.loop();
}, 30);
};
Because the closure (created by the javascript engine in the background), enCLOSES the ‘that’ variable, the function maintains access to it.