The basic concept of a Revealing Module is that you have an Object
which encapsulates its data and behavior:
var Module = (function(){
var privateStuff = {};
var publicStuff = {};
return publicStuff;
})();
However, there are some best practices you should employ when using this pattern. Here's a module ("Modulus
") with some properties for demonstration sake, which employs some of these practices:
function AbstractSomeClass(id) {
this.id = id;
return this;
}
var Modulus = (new (function SomeClass() {
var thus = this;
function NameClass(name){
this.value = thus.name || name;
}
AbstractSomeClass.call(this, 998);
this.name = 'Touring';
this.name = ( new NameClass('Hofstadter') ).value;
return {
id: this.id,
name: this.name
};
})());
Notice the (new (function SomeClass(){ ... })());
syntax. Using new
like this allows you to use the this
keyword inside of the closure. This is handy if you need to inherit properties from another class (AbstractSomeClass.call(this, 998);
) -- However, you'll still need to reveal the properties that you would like to have public, e.g.:
return {
id: this.id,
name: this.name
};
Also notice that we assign this
to thus
-- which allows us to use the Parent-this
inside of a subclass that has its own this
scope (this.value = thus.name || name;
)
Once again, these are just a few of the conventions and best practices that are suggested.