1

I see a lot of namespacing examples with functions but, is it o.k. to declare variables (global to my program) in this way?

var mynamespace = {}; mynamespace.var1 = 5;

or should all variables be placed in functions within the namespace?

agent86
  • 105
  • 12

1 Answers1

0

You should avoid global variables... Use some sort of module pattern instead, e.g.

(function () {
   "use strict";
   var myVar = 'blob';
}());

See http://yuiblog.com/blog/2007/06/12/module-pattern/

EDIT:

More Clarification:

var NS1 = NS1 || {};
NS1.myModule = function () {
        "use strict";
        var myVar = 'blob';
        return  {
            myPublicMethod: function () {
                return myVar;
            }
        };

 }();
MonkeyVoodoo
  • 538
  • 5
  • 17
  • So what is "use strict"? Is that the namespace name I choose? Does that create the namespace without any other code? I went to the blog but not using since I'm not using Yahoo I'm still somewhat confused. Are you saying the above function has no var myNS = (function..., it is in the code as shown? – agent86 May 17 '14 at 15:41
  • "use strict" has nothing to do with the module pattern or global variables, but I added it as it is good practice. It tells the browser to only use the "good parts" of javascript. http://www.yuiblog.com/blog/2010/12/14/strict-mode-is-coming-to-town/ – MonkeyVoodoo May 17 '14 at 15:44
  • 'user strict' is a javascript browser directive that tells the browser to not allow bad js and do some other types of optimizations. – J.Wells May 17 '14 at 15:44
  • Ok, this might be a better approach. Let's say I want create one namespace for the whole project..the master namespace and it's call "NS1". Please show me this in code and I think I'll get it (using the self invoking function method). Thx.in advance. – agent86 May 17 '14 at 16:55