In the particular case that you are showing, there is no significant difference in terms of functionality or visibility.
The source coder probably took this approach as a kind of template, allowing it to define private variables that could be used in defining things like myFunction :
var MyObject = {}; (function(root) { var seconds_per_day = 24 * 60 * 60;
This avoids the calculation of seconds_per_day every time a function is called, and also prevents it from polluting the global area.
However, nothing is fundamentally different from this and just saying
var MyObject = function() { var seconds_per_day = 24 * 60 * 60; return { myFunction: function(foo) { return seconds_per_day; } }; }();
The original encoder may have preferred to be able to add functions to the object using the declarative syntax root.myFunction = function rather than the syntax of the object / property myFunction: function . But this difference mainly depends on preferences.
However, the structure taken by the source encoder has the advantage that properties / methods can be easily added elsewhere in the code:
var MyObject = {}; (function(root) { var seconds_per_day = 24 * 60 * 60; root.myFunction = function(foo) { return seconds_per_day; }; })(MyObject); (function(root) { var another_private_variable = Math.pi; root.myFunction2 = function(bar) { }; })(MyObject);
Bottom line, there is no need to apply this approach if you do not need it, but there is no need to change it, since it works great and actually has some advantages.
user663031 Nov 06 '14 at 20:24 2014-11-06 20:24
source share