Game Development Reference
In-Depth Information
The design pattern for putting classes in namespaces uses a JavaScript mechanism that lets you
define and call a function at the same time. Perhaps you recall using this before, when defining the
function to request the next game-loop iteration:
var requestAnimationFrame = (function () {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function (callback) {
window.setTimeout(callback, 1000 / 60);
};
})();
Here the variable requestAnimationFrame contains the result of a function that is defined and
immediately called. In a very similar way, you can put the definition of a class in such a function.
Have a look at the following example:
var powerupjs = (function (module) {
function Vector2(x, y) {
this.x = typeof x !== 'undefined' ? x : 0;
this.y = typeof y !== 'undefined' ? y : 0;
}
Object.defineProperty(Vector2, "zero",
{
get: function () {
return new powerupjs.Vector2();
}
});
Vector2.prototype.equals = function (obj) {
return this.x === obj.x && this.y === obj.y;
};
// add more methods and properties
...
module.Vector2 = Vector2;
return module;
})({});
This example creates a function that expects an object literal module as a parameter. In the function,
you create the Vector2 class and define its properties and methods. You assign that class to a
variable in the module variable, which you then return. The function is executed by passing an empty
object literal to the function. The result of the function is stored in the variable powerupjs , which now
contains a variable called Vector2 that refers to the class Vector2 . For the next class you define,
you'll pass the variable powerupjs instead of an empty object literal, so that the powerupjs variable
 
Search WWH ::




Custom Search