Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I always use JavaScript namespaces even for simple projects. I'm using following namespace pattern (found in JavaScript Patterns):</p> <pre><code>var SN = SN || {}; SN.namespace = function(ns_string) { var parts = ns_string.split('.'), parent = SN, i; // strip redundant leading global if(parts[0] === "SN") { parts = parts.slice(1); } for(i = 0; i &lt; parts.length; i++) { //create property if it doesn't exist if(typeof parent[parts[i]] === "undefined") { parent[parts[i]] = {}; } parent = parent[parts[i]]; } return parent; } </code></pre> <p>You can use it like this:</p> <pre><code>SN.namespace('SN.subnamespace1.subnamespace3'); SN.subnamespace1.subnamespace3.object = function() {}; </code></pre> <p>It's good approach to create namespaces in this way when working in team - nobody will overwrite your namespace. Also you can easily specify one place (file) when team will create namespaces so it will be easy to see what name is taken or not.</p> <p>Then I'm using closures to separate private context of objects if needed (as you have in your example as well). Closures are probably the most powerful tool in JS (functional programming). You can create contexts which persist until deletion of every inner object.</p> <p>I also like <a href="https://stackoverflow.com/a/15674109/571230">getInstance JavaScript pattern</a> and revelation pattern (it works with <code>new</code> and without as well):</p> <pre><code>var cat = function(name, color, size) { var _color = color, _size = size, _name = name, getName = function() { return _name; }, getColor = function() { return _color; }, getSize = function() { return _size; }; return { color: getColor, size: getSize, name: getName } }; var new_cat1 = new cat('a', 'b', 1); var new_cat2 = new cat('c', 'd', 2); var new_cat3 = cat('e', 'f', 3); console.log(new_cat1.name()); console.log(new_cat2.name()); console.log(new_cat3.name()); </code></pre> <p>Also read the book I mentioned on the beginning - personally I think it's best source of good practices when programming in JS. I learnt a lot from this book!</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload