Reputation: 837
I came across a JS file which was built in a strange manner:
var modal = (function(){
var method = {};
// Center the modal in the viewport
method.center = function () {};
// Open the modal
method.open = function (settings) {};
// Close the modal
method.close = function () {};
return method;
}());
I understand the part of wrapping a function into the "modal" object, but why bind all the functions to method
and then return it at the end?
Upvotes: 5
Views: 162
Reputation: 43235
This is a design pattern to group functionalities into modules, and to get rid of global variables. This leads to better code.
The function call creates a 'closure' i.e. a scope for all the variables declared within that function, they stay even after the function has exited, and they are not visible outside the function.
var modal = (function(){
var method = {};
// Center the modal in the viewport
method.center = function () {};
// Open the modal
method.open = function (settings) {};
// Close the modal
method.close = function () {};
return method;
}()); // This function call here creates a "closure" ( scope )
Now to make certain members of the module available outside the module, they need to be returned from the function, here return method
does exactly that, making method
a public object of the module , which can be used outside.
Instead of creating invididual variables like open
, close
etc, the related functions are assigned as properties ( keys of the object ) to the main method
object, so that returning the single object makes all the related functions accesible. This also serves the purpose of reducing the number of identifiers (names ) within the closure scope.
Read this very good article on this modular
pattern :
http://www.yuiblog.com/blog/2007/06/12/module-pattern/
Upvotes: 6
Reputation: 700322
For that specific code, there is no advantage. It does the same as:
var modal = {
// Center the modal in the viewport
center: function () {},
// Open the modal
open: function (settings) {},
// Close the modal
close: function () {},
};
However, if you put a local variable in the function, that's a different matter:
var modal = (function(){
// a variable that is private to the object
var local = 'hello world';
var method = {};
// Center the modal in the viewport
method.center = function () {};
// Open the modal
method.open = function (settings) {};
// Close the modal
method.close = function () {};
return method;
}());
Now all the methods in the object can access the private variable, but it's not directly reachable from outside the object.
Upvotes: 3