1

我有一部分插件使用私有变量并公开公共方法:

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

我知道的唯一选择是使用对象文字:

JSBIN 2

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


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

问题

如何封装私有字段并仍然防止使用myWorld被实例化>1 times

4

5 回答 5

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);};
  }
})();
于 2013-03-07T15:25:57.270 回答
2

闭包是定义范围的好工具:

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


   myWorld.do1();

您可能想查看免费的学习 JavaScript 设计模式一书

于 2013-03-07T15:26:02.273 回答
1
var a = new function myWorld()
{
  var myPrivate=1;
  this.do1=function (){alert(myPrivate);} ;
}

This makes myWorld available only inside the function. If you don't event want it accessable there, then remove the name.

于 2013-03-07T15:29:21.253 回答
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
于 2013-03-07T15:56:07.963 回答
1

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

var myWorld = (function() { 
    var myPrivate = 1;
    return { ... };
}());
于 2013-03-07T15:26:14.227 回答