Trying to implement the singleton pattern within CommonJS modules, using Browserify. So far:
// foo.js
var instance = null;
var Foo = function(){
if(instance){
return instance;
}
this.num = 0;
return instance = new Foo();
}
Foo.prototype.adder = function(){
this.num++;
};
module.exports = Foo();
// main.js
var foo = require('./foo.js');
console.log(foo.num); // should be 0
foo.adder(); // should be 1
var bar = require('./foo.js');
console.log(bar.num); // like to think it'd be 1, not 0
First problem is that I get a maximum call stack exceeded
error when I load the built JS file in the browser, but secondly, am I approaching this correctly? Is this possible?
exports = Singleton; but we export the instance of the class module. exports = new Singleton() instead. Node. JS will cache and reuse the same object each time it's required.
Node. js modules can behave like Singletons, but they are not guaranteed to be always singleton.
CommonJS is a module formatting system. It is a standard for structuring and organizing JavaScript code. CJS assists in the server-side development of apps and it's format has heavily influenced NodeJS's module management.
Node. js, however, supports the CommonJS module format by default.
First problem is that I get a maximum call stack exceeded error
Well, that comes from your Foo
function recursively calling new Foo
…
but secondly, am I approaching this correctly?
No. For singletons, you don't need a "class" with a constructor and a prototype - there will only ever be one instance. Simply create one object, most easily with a literal, and return that:
module.exports = {
num: 0,
adder: function(){
this.num++;
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With