HTML and CSS Reference
In-Depth Information
Variable scope in JavaScript
In JavaScript, we want to have as few global variables as possible. Variables are global when
they are atached to the highest scope of the runime environment. In a web browser, this
refers to a variable that is atached to a window scope. A variable that is created with the
var keyword lives inside the scope of the funcion that encloses it.
This is why we put all the logic inside a self-execuing anonymous funcion. This ensures that
by default, we will not pollute the global scope with our game logic variables. The following
code block shows how to create each module with one global game variable and one local
game variable inside a self-execuing-anonymous funcion:
var game = this.colorQuestGame = this.colorQuestGame || {};
We will intenionally create one global variable named colorQuestGame to act as the
namespace. In the later secions, we will put diferent logic modules into diferent iles
under the same global object.
The this.colorQuestGame || {}; declaraion means that, by default, it will use the
exising colorQuestGame variable if it was already declared previously. Otherwise, it will
be a new empty object. We will put this line of declaraion into every ile.
This scoping feature is also useful when we need to encapsulate logic into private funcions.
For example, the following code shows how we can create private funcions that are only
accessible inside a specific scope to help extract the code:
Composition.createFromSequence = function(sequence) {
// helper functions
var privateHelperA = function() {}
var privateHelperB = function() {}
// end helper functions
// use your private helper functions here.
Inside any method, we can declare local scoped funcions to help extract the logic and to
make the code more readable.
Classified intel
For performance, we usually place scripts at the end of Document Object Model ( DOM )
and just before the closing of the </body> tag. This is because script loading may block the
loading of DOM and cause the webpage to load slower. For more details, please have a look
at the Yahoo performance rule, Put Scripts at the Botom , at
com/performance/rules.html#js_bottom .
Search WWH ::

Custom Search