Reputation: 53
I'm writing javascript singleton class and want to use singleton pattern like this:
function TestClass() {
var self = TestClass.prototype;
if (self.instance) return self.instance;
self.instance = this;
//methods and props declarations
}
var x = new TestClass;
var y = new TestClass;
console.log(x === y); // true
It seems to be worked as i expected, but i worry about memory leaks. So i decided to ask experts, if it is the correct solution
Upvotes: 2
Views: 282
Reputation: 11740
Your code is not wrong per se but not good either. you are not creating a singleton, just "hijack" the prototype. #svidgen gave a correct response.
Upvotes: 0
Reputation: 14302
Not exactly. I generally do something like this when I need a singleton:
function TestClass() {
if (TestClass.__singleton) {
return TestClass.__singleton;
}
// begin construction ...
this.a = function() { };
this.b = 1;
// ... end construction
TestClass.__singleton = this;
} // TestClass
var x = new TestClass(); // creates a new TestClass and stores it
var y = new TestClass(); // finds the existing TestClass
console.log(x === y); // true
y.b = 2;
x.c = 3;
console.log(x.b === y.b && x.c === y.c); // true
If my understanding is correct, subsequent TestClass
instantiations, in this case, will create a small, partially-defined TestClass
object, but will immediately mark them for garbage collection when TestClass.__singleton
is returned.
Upvotes: 1