2

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()
asked Jul 25, 2012 at 3:25
1
  • 2
    What do you mean with superior? Commented Jul 25, 2012 at 3:26

2 Answers 2

7

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
Sign up to request clarification or add additional context in comments.

2 Comments

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.
@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.
0

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.

answered Jul 25, 2012 at 3:31

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.