Answer the question
In order to leave comments, you need to log in
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
Because the objects ( o
and 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
<sarcasm>Because a singleton is an antipattern.</sarcasm>
In general, read this:
- constructor functions
- hoisting
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question