Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I agree with you, the simplest way is to use a object literal, but if you want <em>private</em> members, you could implement taking advantage of <a href="http://www.jibbering.com/faq/faq_notes/closures.html" rel="nofollow noreferrer">closures</a>:</p> <pre><code>var myInstance = (function() { var privateVar; function privateMethod () { // ... } return { // public interface publicMethod1: function () { // private members can be accessed here }, publicMethod2: function () { // ... } }; })(); </code></pre> <p>About the <code>new function(){}</code> construct, it will simply use an anonymous function as a <a href="https://developer.mozilla.org/En/Core_JavaScript_1.5_Guide/Creating_New_Objects/Using_a_Constructor_Function" rel="nofollow noreferrer"><code>constructor function</code></a>, the context inside that function will be a new object that will be returned.</p> <p><strong>Edit:</strong> In response to the <a href="https://stackoverflow.com/questions/1895635/javascript-singleton-question#comment-1799557">@J5's comment</a>, that is simple to do, actually I think that this can be a nice example for using a <em>Lazy Function Definition</em> pattern:</p> <pre><code>function singleton() { var instance = (function() { var privateVar; function privateMethod () { // ... } return { // public interface publicMethod1: function () { // private members can be accessed here }, publicMethod2: function () { // ... } }; })(); singleton = function () { // re-define the function for subsequent calls return instance; }; return singleton(); // call the new function } </code></pre> <p>When the function is called the first time, I make the object instance, and reassign <code>singleton</code> to a new function which has that object instance in it's closure.</p> <p>Before the end of the first time call I execute the re-defined <code>singleton</code> function that will return the created instance.</p> <p>Following calls to the <code>singleton</code> function will simply return the <code>instance</code> that is stored in it's closure, because the new function is the one that will be executed.</p> <p>You can prove that by comparing the object returned:</p> <pre><code>singleton() == singleton(); // true </code></pre> <p>The <code>==</code> operator for objects will return <code>true</code> only if the object <em>reference</em> of both operands is the same, it will return false even if the objects are identical but they are two different instances:</p> <pre><code>({}) == ({}); // false new Object() == new Object(); // false </code></pre>
 

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