-2

Please refer the following fiddle : http://jsfiddle.net/hBvSZ/5/

var NewObject = function () { 
//Singleton should be accessible here
    this.method1 = function() { }
};

Also can we pass singleton in such a way that the methods of singleton are just accessible to the NewObject ?

Ecko123
  • 308
  • 1
  • 4
  • 16
  • possible duplicate of [Simplest/Cleanest way to implement singleton in JavaScript?](http://stackoverflow.com/questions/1479319/simplest-cleanest-way-to-implement-singleton-in-javascript) – Colin Brock Nov 30 '13 at 06:02
  • It's likely you have an [XY Problem](http://www.perlmonks.org/?node_id=542341) and you don't need a singleton at all. – maček Nov 30 '13 at 06:11
  • The question is not to implement singleton, if you can check the fiddle I've already shown a singleton. The question is how we can pass that to an object in such a way that constructor automatically creates the same singleton instance. People do google first before asking ..!!! – Ecko123 Dec 03 '13 at 03:45

2 Answers2

0

Store the singleton in a variable:

var singleton;
function NewObject () {
    if (typeof singleton == 'undefined') {
        // initialize new object here.
    }
}

That's the basic idea.

To avoid global namespace pollution you can use a closure:

var NewObject = (function(){
    var singleton;
    return function () {
        if (typeof singleton == 'undefined') {
            // initialize new object here.
        }
    }
})();
slebetman
  • 109,858
  • 19
  • 140
  • 171
0

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();
maček
  • 76,434
  • 37
  • 167
  • 198