R
R
Rapen2016-10-06 17:52:01
JavaScript
Rapen, 2016-10-06 17:52:01

Why is this pattern not correct?

var obj = {};
  
var Singleton = function(){
 if(!obj) { 
var obj = {};
}
 
  return obj;
  
  }
  
var o  = new Singleton();
var o1 = new Singleton();

o.prop = 's'; 
console.log(o === o1);  //false
console.log(o1.prop); //undefined

Answer the question

In order to leave comments, you need to log in

3 answer(s)
F
Fat Lorrie, 2016-10-06
@Free_ze

Because the objects ( oand o1) are different, each has its own obj.
The very idea of ​​a singleton is that it is one object (type) for the entire program.

function Singleton () {
    if (Singleton._instance) return Singleton._instance;
    Singleton._instance = this;
};

var o = new Singleton();
var o1 = new Singleton();
console.log(o === o1); // true

o.prop = 's';
console.log(o1.prop); // s

M
Mikhail Osher, 2016-10-06
@miraage

<sarcasm>Because a singleton is an antipattern.</sarcasm>
In general, read this:
- constructor functions
- hoisting

T
T_y_l_e_r, 2016-10-06
@T_y_l_e_r

Singleton always returns only 1 object and does not create a new one.
You have a new object generated with each new

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question