I was looking over the js source code for Scrabb.ly.
I've noticed that they would do something like so for each of their distinct "classes":
var Board = (function() {
var self = {};
// settings for board
self.options = {
debug: true,
addedPlayTiles: function() {},
clearedPlayTiles: function() {}
};
// set to true once the board has been setup
self.isSetup = false;
// quick access to square elements
self.squares = {};
self.squareCount = 0;
self.setup = function(options) {
self.log("Setting up board!");
// set options
_.each(options, function(val, key) {
self.options[key] = val;
});
return self;
})();
Some code from the middle has been omitted but this should give you the general idea.
- What is the purpose of the the following:
(function() { // code })();
Is this the module pattern that I've seen talked about? Is this meant to keep the global namespace clean? - What does this line mean?:
var self = {}
Is the self object used to exposed 'public' members? How would you define a private function or variable? - How would you instantiate multiple "Boards" if you wanted to?