Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Singleton pattern with Browserify/CommonJS

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?

like image 375
benhowdle89 Avatar asked Jun 18 '14 10:06

benhowdle89


People also ask

Is module exports a singleton?

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.

Is node A module singleton?

Node. js modules can behave like Singletons, but they are not guaranteed to be always singleton.

What is CommonJS format?

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.

Does noj use CommonJS?

Node. js, however, supports the CommonJS module format by default.


1 Answers

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++;
    }
};
like image 128
Bergi Avatar answered Sep 28 '22 04:09

Bergi