Even though I doubt you actually need the Singleton pattern in JavaScript, here's how I'd do it:
var Client = (function() {
var instance;
var Client = function() {
};
Client.prototype.hello = function() {
console.log("hello");
};
return {
getInstance: function() {
if (!instance) {
instance = new Client();
}
return instance;
},
otherHelper: function() {
console.log("look i'm helping!");
},
};
})();
var a = Client.getInstance();
var b = Client.getInstance();
a.hello(); // "hello"
b.hello(); // "hello"
console.log("a === b", a === b); // true
Client.otherHelper(); // look i'm helping!
If you're using this server-side (node.js for example), you could do this
// client.js
var instance;
var getInstance = function getInstance() {
if (!instance) {
instance = new Client();
}
return instance;
};
var Client = function Client() {
};
Client.prototype.hello = function() {
console.log("hello");
};
exports.getInstance = getInstance;
Then usage is simple
// app.js
var Client = require("./client");
var myClient = Client.getInstance();