Create only one instance of a constructor function?

I have a part of a plugin that uses private variables and provides a public method:

JSBIN 1

function  myWorld()
    {
      var myPrivate=1;
      this.do1=function (){alert(myPrivate);} ;
    }

var a=new  myWorld();

a.do1() //1
alert(a.myPrivate); //undefined (as it should be)

But I want to not do this again: new myWorld();

The only option I know is with an object literal:

Jsbin 2

var myWorld=
    {
      myPrivate:1,
      do1:function (){alert(this.myPrivate);} 
    }


alert(myWorld.myPrivate); //1 ( ouch....)
myWorld.do1() //1

Question

How to encapsulate private fields and still deny use myWorldfor launch >1 times?

+1
source share
5 answers

Closing is a great tool for defining an area:

  var myWorld= (function(){
    var myPrivate = 1;
    return {
      do1:function (){alert(myPrivate);} 
    }
  }());


   myWorld.do1();

You can check out the Free Exploring JavaScript Design Templates

+2
source

Try something in this direction:

(function(){
  var instanciated = false;
  window.myWorld = function() {
    if( instanciated) throw new Error("myWorld can only be instanciated once!");
    instanciated = true;
    var myPrivate = 1;
    this.do1 = function(){alert(myPrivate);};
  }
})();
+2
source

IIFE:

var myWorld = (function() { 
    var myPrivate = 1;
    return { ... };
}());
+1
var a = new function myWorld()
{
  var myPrivate=1;
  this.do1=function (){alert(myPrivate);} ;
}

myWorld . , , .

+1
source

You can use a singleton template to support a single instance of an object. Sort of:

(function (global) {
    var _inst;

    global.myWorld = function () {
        if (_inst) throw new Error("A myWorld instance already exists. Please use myWorld.getInstance()");
        _inst = this;
    };

    global.myWorld.prototype = {
        do1: function() {
            console.log("do1");
        }
    };

    global.myWorld.getInstance = function() {
        if (_inst) return _inst;
        return new myWorld();
    };
}(window));

var world = new myWorld();
var world2 = myWorld.getInstance();
console.log(world === world2); // true
var world3 = new myWorld(); // throws Error
+1
source

All Articles