Reputation: 7801
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.
(function() { // code })();
Is this the module pattern that I've seen talked about? Is this meant to keep the global namespace clean?var self = {}
Is the self object used to exposed 'public' members? How would you define a private function or variable?Upvotes: 7
Views: 430
Reputation: 344261
As mentioned in the other answer, that's the Module Pattern.
It is also known as the YUI Module Pattern or the Yahoo Module Pattern, mainly because it was made popular by this blog article:
Regarding point 3, the Module Pattern is intended to be a singleton. However, the Module Pattern is easily transformed into a Constructor Pattern. You may want to check out the following presentation by Douglas Crockford for more information on this topic:
Upvotes: 4
Reputation: 40298
var self = {}
should have the effect of initializing self as an empty object literal; if self already existed, it should delete the old values and reinitialize as an empty array.
Upvotes: 1
Reputation: 32097
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, self
contains the "public" methods and properties, as it were. Any variables that aren't defined in self
are not visible to the outside because of the closure properties. However, any functions defined in self
still 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.. mainly arguments
and this
.
If you want to define multiple instances of this object, you would remove the parentheses (var Board = function () { ... }
) and then use var obj = Board()
to create an object. Note that it does not use the new
operator.
Upvotes: 11