Note that there are some explanatory texts on larger screens.

plurals
  1. POJavaScript namespacing - looking for a simple and efficient approach
    text
    copied!<p>I would like to implement JavaScript Namespacing in a project. My co-workers and I are not specialists in JavaScript and therefore we are looking for a simple and efficient namespacing approach. Readability is a great asset, we are Java developers and easy preys for JavaScript traps.</p> <p>We have written the following prove of concept:</p> <pre><code>&lt;html&gt;&lt;body&gt;&lt;script&gt; var mynamespace = {}; mynamespace.variable = "inside mynamespace"; mynamespace.level1 = {}; mynamespace.level1.level2 = {}; (function(){ this.variable = "inside mynamespace.level1"; this.print = function(){ return "print() : " + this.variable }; }).apply(mynamespace.level1); (function(){ this.variable = "inside mynamespace.level1.level2"; this.print = function(){ return "print() : " + this.variable }; }).apply(mynamespace.level1.level2); // We can use "that" instead of "this"; however I do not see any benefit in doing it... (function(){ if(!mynamespace.level1.level2b){ this.level2b = {}; var that = this.level2b }; that.variable = "inside mynamespace.level1.level2b"; that.print = function(){ return "print() : " + this.variable }; }).apply(mynamespace.level1); document.write(mynamespace.level1.print() + "&lt;br&gt;"); // print() : inside mynamespace.level1 document.write(mynamespace.level1.variable + "&lt;br&gt;");// inside mynamespace.level1 document.write(mynamespace.level1.level2.print() + "&lt;br&gt;");// print() : inside mynamespace.level1.level2 document.write(mynamespace.level1.level2.variable + "&lt;br&gt;");// inside mynamespace.level1.level2 document.write(mynamespace.level1.level2b.print() + "&lt;br&gt;");// print() : inside mynamespace.level1.level2b document.write(mynamespace.level1.level2b.variable + "&lt;br&gt;");// inside mynamespace.level1.level2b document.write(mynamespace.variable + "&lt;br&gt;");// inside mynamespace document.write(mynamespace.something + "&lt;br&gt;");// undefined &lt;/script&gt;&lt;/body&gt;&lt;/html&gt; </code></pre> <p>=== Questions ===</p> <p>Q1. Do you think that it is a good approach?</p> <p>Q2. Is there any pitfall we could run into?</p> <p>Q3. Would you have a better suggestion (please, consider simplicity, readability)?</p> <p>Any help is highly appreciated.</p> <p>Cheers,</p> <p><strong>EDIT:</strong> We are going to use jQuery. So, you there is a better approach using jQuery we would consider it.</p>
 

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