Note that there are some explanatory texts on larger screens.

plurals
  1. POJavaScript singleton pattern and 'this'
    primarykey
    data
    text
    <p>After reading a lot of articles on singleton pattern, and making some tests, I found no difference between the singleton pattern like this (<a href="http://jsfiddle.net/bhsQC/1/" rel="nofollow">http://jsfiddle.net/bhsQC/1/</a>):</p> <pre><code>var TheObject = function () { var instance; function init() { var that = this; var foo = 1; function consoleIt() { console.log(that, foo); } return { bar: function () { consoleIt() } }; } return { getInstance: function () { if (!instance) { instance = init(); } return instance; } }; }(); var myObject = TheObject.getInstance(); myObject.bar(); </code></pre> <p>and code like this (<a href="http://jsfiddle.net/9Qa9H/3/" rel="nofollow">http://jsfiddle.net/9Qa9H/3/</a>):</p> <pre><code>var myObject = function () { var that = this; var foo = 1; function consoleIt() { console.log(that, foo); } return { bar: function () { consoleIt(); } }; }(); myObject.bar(); </code></pre> <p>They both make only one instance of the object, they both can have "private" members, <code>that</code> points to <code>window</code> object in either of them. It's just that the latter one is simpler. Please, correct me if I'm wrong.</p> <p>Using standard constructor like this (<a href="http://jsfiddle.net/vnpR7/2/" rel="nofollow">http://jsfiddle.net/vnpR7/2/</a>):</p> <pre><code>var TheObject = function () { var that = this; var foo = 1; function consoleIt() { console.log(that, foo); } return { bar: function () { consoleIt(); } }; }; var myObject = new TheObject(); myObject.bar(); </code></pre> <p>has the advantage of correct usage of <code>that</code>, but isn't a singleton.</p> <p>My question is: <strong>what are the overall advantages and disadvantages of these three approaches?</strong> (If it matters, I'm working on a web app using Dojo 1.9, so either way, this object will be inside Dojo's <code>require</code>).</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.
 

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