1) In the following code, what is the reasoning behind making gameOfLive a variable and not just function gameOfLife()?
2) What is gol? It seems like an array, but I am unfamiliar with the syntax or what its called.
I am studying http://sixfoottallrabbit.co.uk/gameoflife/
if (!window.gameOfLife) var gameOfLife = function() {
var gol = {
body: null,
canvas: null,
context: null,
grids: [],
mouseDown: false,
interval: null,
control: null,
moving: -1,
clickToGive: -1,
table: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(''),
tableBack: null,
init: function(width, height) {
gol.body = document.getElementsByTagName('body')[0];
gol.canvas = document.createElement('canvas');
if (gol.canvas.getContext) {
gol.context = gol.canvas.getContext('2d');
document.getElementById('content').appendChild(gol.canvas);
gol.canvas.width = width;
gol.canvas.height = height;
gol.canvas.style.marginLeft = "8px";
gol.control = document.getElementById('gridcontrol');
gol.canvas.onmousedown = gol.onMouseDown;
gol.canvas.onmousemove = gol.onMouseMove;
gol.canvas.onmouseup = gol.onMouseUp;
gol.addGrid(48,32,100,44,8);
gol.refreshAll();
gol.refreshGridSelect(-1);
gol.getOptions(-1);
gol.genTableBack();
} else {
alert("Canvas not supported by your browser. Why don't you try Firefox or Chrome? For now, you can have a hug. *hug*");
}
},
}
}
is a function expression, whereas
is a function declaration.
To quote Juriy ‘kangax’ Zaytsev about Function expressions vs. Function declarations:
In this case, as Joel Coehoorn mentions in a comment,
gameOfLifeis defined conditionally, so it’s needed to use a function expression.A general use case for these conditionally defined functions is to enhance JavaScript functionality in browsers that don’t have native support for newer functions (not available in previous ECMAScript/JavaScript versions). You don’t want to do this using function declarations, as those will overwrite the native functionality anyway, which is most likely not what you want (considering speed, etc.). A short example of this:
One major drawback of function expressions is that you in fact assign an anonymous function to a variable. This can make debugging harder, as the function name is usually not known when script execution halts (e.g., on a breakpoint you set). Some JavaScript debuggers, like Firebug, try to give the name of the variable the function was assigned to, but as the debugger has to guess this by parsing the script contents on-the-fly, this can be too difficult (which results in a
(?)()being shown, instead of a function name) or even be wrong.(for examples, read on on the page, though its contents are not entirely suitable for beginners)