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?
It’s called the Module Pattern.
The parentheses around the function mean it’s being evaluated immediately after being defined — so in essence it’s a Singleton. Since it’s an anonymous function, the definition is not stored – so you cannot readily create new instances of this object without a few modifications (which will be discussed later).
You are correct,
selfcontains the “public” methods and properties, as it were. Any variables that aren’t defined inselfare not visible to the outside because of the closure properties. However, any functions defined inselfstill have access to the private variables because in Javascript, functions maintain access to the context (including variables) in which they were defined — with a few exceptions.. mainlyargumentsandthis.If you want to define multiple instances of this object, you would remove the parentheses (
var Board = function () { ... }) and then usevar obj = Board()to create an object. Note that it does not use thenewoperator.