只创建一个构造函数的实例?

时间:2013-03-07 15:23:19

标签: javascript

我有一个插件的部分,它使用私有变量并公开 public 方法:

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)

但我想再次阻止这样做:new myWorld();

我所知道的唯一选择是使用object literal:

JSBIN 2

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


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

问题

如何封装私有字段并仍然阻止来自myWorld的用户被>1 times

5 个答案:

答案 0 :(得分:2)

尝试以下几点:

(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);};
  }
})();

答案 1 :(得分:2)

闭包是定义范围的绝佳工具:

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


   myWorld.do1();

您可能需要查看免费的Learning JavaScript Design Patterns图书

答案 2 :(得分:1)

您可以在IIFE中隐藏私人变量:

var myWorld = (function() { 
    var myPrivate = 1;
    return { ... };
}());

答案 3 :(得分:1)

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

这使myWorld仅在函数内可用。如果您没有想要在那里访问它,请删除该名称。

答案 4 :(得分:1)

您可以使用单例模式来维护对象的一个​​实例。类似的东西:

(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