Can a JS guru out there explain why this:
$$={}
(function(x){
x.newModule = {
func: function(){...}
};
})($$);
$$.newModule.func()
is superior to this?
$$.newModule = {
func: function() {...}
}
$$.newModule.func()
-
2What do you mean with superior?Danilo Valente– Danilo Valente2012年07月25日 03:26:20 +00:00Commented Jul 25, 2012 at 3:26
2 Answers 2
The extra function gives you an extra local scope that you might want to use (though it is not in your short example).
(function(x){
var privateFunction = function() {};
var privateCounter = 1;
x.newModule = {
func: function(){...}
};
})($$);
answered Jul 25, 2012 at 3:29
Thilo
264k107 gold badges527 silver badges674 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
nnnnnn
Also,
x only saves one character over $$, but a real-world example might have x and myNamespace.mySubNamespace.someObject so if you needed to reference the object repeatedly to add multiple methods and/or properties giving it a one-character alias makes the code neater and easier to read.Thilo
@nnnnnn: And the module author might be a different person than the module user, and with this "export"-like syntax, each gets to choose her own favorite names.
In the first pattern you can have private methods and variables which are not possible in the second pattern. That is the reason the first pattern is superior.
Comments
lang-js