There's two distinct patterns that you're mentioning, I think.
Anonymous Closures
The first is using an anonymous function to wrap a block of code in order to create a closure:
var outer = (function() {
var inner = "now you see me!";
return inner + " now you don't"
})()
The anonymous function creates a new scope for var
-defined variables. In effect, this allows you to define variables that are only visible within that particular function.
In the example above, you have access to inner
within the function, but it is not defined outside of it.
"Classes"
The second is a common pattern for defining "classes" in JavaScript:
var MyClass = (function() {
function MyClass(arg) {
this.arg = arg
}
return MyClass
})()
By defining the constructor function within a closure, you can be sure that your class is well contained. It also enables you to share class-wide state or private helper methods without polluting the global namespace, or resorting to placing them as properties on your class constructor's prototype.