Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>billy moon shows a good start, but the problem with using object literals, is that you cannot cross reference other fields/functions/properties.</p> <p>I much prefer the revealing module pattern (see <a href="http://www.wait-till-i.com/2007/08/22/again-with-the-module-pattern-reveal-something-to-the-world/" rel="nofollow">http://www.wait-till-i.com/2007/08/22/again-with-the-module-pattern-reveal-something-to-the-world/</a>)</p> <p>the revealing module pattern combines a self-executing function, an exploitation (of sorts) of closures to provide internal private functions/fields, and allows you to pass params to initialise your namespaced object.</p> <pre><code>var namespacedObject = function(param) { var settings = param || someDefaultSetting, //default if no param supplied somePrivateField = "someValue", somePublicField = "i'm public"; //define some method we will later make public function toggleComments(){ $("comments-section").hide(); $("comments-button").click(function (){ $(this).value= somePrivateField; return false; }); } //this is where the magic happens, //return object with all public fields/functions return { toggleComments : toggleComments, somePublicField : somePublicField }; }(someParam); </code></pre> <p>You can see that the namespaced object contains a private field <code>somePrivateField</code>, which can be referenced from publicly accessible methods. Also, notice i have exposed a public field, and accepted some params which i may use/reference in functions etc (and you can default it to some default if nothing is passed in.</p> <p>can be used like this:</p> <pre><code>namespacedObject.toggleComments(); alert(namespacedObject.somePublicField); alert(namespacedObject.somePrivateField); //undefined - it's private of course! </code></pre> <p>one reason i like this is that it's very easy to see what is public/private by just glancing at the object literal returned from the self-executing function</p> <p>Hope that's helpful</p>
    singulars
    1. This table or related slice is empty.
    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. 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