5

如果我们想使用私有变量,我有一些关于在 javascript 中创建单例的两种方法的阅读 - 简单的对象文字方式和另一种使用闭包技术。

我正在寻找一个实用功能,例如

Singleton(classname);

无论什么类——“构造函数”我在这里作为参数传入,Singleton 方法都将这个类转换为一个 Singleton 对象,加上在调用new Classname()if 有人再次触发 new classname() 之后他/她得到了一些new Error ( "Already instantiated once, this is Singleton" );

用例如下 -

function Circle() {this.name = "Circle";}
SingleTon(Circle);
var circle1 = new Circle(); // returns the circle instance
var circle2 = new Circle(); // throws Error "Already instantiated once, this is Singleton"

我只是想在这里定义“单例”方法。

我见过类似的例子,其中使用 getInstance 方法来获取实例,例如 - Singleton.getInstance(Circle)等,但我正在寻找上面的特定问题,另一个程序员习惯于以“新”方式创建实例试图在他的代码某处第二次触发new Circle(); 并收到错误。

以这种方式创建单例是一个问题,但主要问题是抛出“错误”,据我了解,Circle 构造函数需要在单例函数的某处进行修改,不知道如何完成此操作。

有什么解决办法吗?

提前致谢 !!

4

3 回答 3

4
function Singleton(param){
    var count = 0, old = window[param];
    window[param] = function(){
         if(++count <= 1) return old;
         else alert('NO WAY!'); 
    }
}

你可以这样称呼它:

Singleton('Circle');

演示:http: //jsfiddle.net/maniator/7ZFmE/

请记住,这仅在Circle或任何其他函数类位于全局window命名空间中时才有效。任何其他命名空间中的任何内容都需要更多操作才能使其充分工作。

于 2012-11-05T19:51:17.337 回答
1

尝试这个:

Circle = function () {
  if (!(this instanceof Circle)) {
    // called as function
    return Circle.singleton || (Circle.singleton = new Circle());
  }
  // called as constructor

  this.name = "the circle";
};

现在,如果没有 new 运算符,您将使用单例或新的

var mycircle = Circle();

请注意,我在示例中使用了全局名称,您也可以这样做

var Circle = window.Circle = function () { //...
于 2012-11-05T20:09:50.190 回答
0

当然,您也可以创建单个实例对象,并可以使用诸如以下的闭包:

var singlecircle = (new function(name) {
         this.name = name || "Default circle";}('squared')
    );
singlecircle.name; //=> 'squared'
于 2012-11-06T10:22:12.493 回答