I’m confused by a javascript design pattern I’m reading about:
var class = (function() {
...a bunch of code...
return {
.. some more code..
;
// or, in some cases
return function(constructorArgs) {
};
})();
My question is: What is the return statement doing? Why is it there? I’m confused because no-one wants to mention it or talk about it.
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:
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
innerwithin the function, but it is not defined outside of it.“Classes”
The second is a common pattern for defining “classes” in JavaScript:
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.