William Jiang

JavaScript,PHP,Node,Perl,LAMP Web Developer – http://williamjxj.com; https://github.com/williamjxj?tab=repositories

JavaScript: 3 ways to implement Singleton

JavaScript: 2+1 ways of Singleton implementation

Here I list 2 ways of Singleton implementation, which refers to Stoyan Stefanov’s JavaScript Patterns.

//1. rewrite constructor function in a closure:
var Singleton = (function() {
  var instance;
  Singleton = function Singleton() {
    if(instance) {
      return instance;
    }

    instance = this;

    this.start_time = 0;
    this.others = "others";
  };
}());

// more directly:
function Singleton() {
  var instance = this;

  this.start_time = 0;
  this.others = "others";

  Singleton = function() {
    return instance;
  };

}

//2. pretty cool: use static attribute of constructor:
function Singleton() {
  if(typeof Singleton.instance === 'object') {
    return Singleton.instance;
  }

  this.start_time = 0;
  this.others = "others";

  Singleton.instance = this;
}

And, a parasitic constructor function mode:


function Singleton() {
  var o;
  //rewrite constructor,
  //so next time directly return Singleton instance.
  Singleton = function Singleton() {
    return o;
  }

  // for dynamic prototype mode
  Singleton.prototype = this;

  // o.__proto__=Singleton
  o = new Singleton();
  //
  o.constructor = Singleton;
  this.start_time = 0;
  this.others = "others";

  return o;  //not return this!
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: