只允许在javascript中使用类成员的一个实例

mar*_*tch 0 javascript ecmascript-6

我正在谷歌地图API前面创建一个帮助类 - 只是为了学习.

我想在我的类中只保留一个google.maps.Map对象的实例,即使有人决定实例化该类的另一个实例.

我来自.NET背景,概念很简单 - 但是我仍然适应javascript(和ES6),所以任何指针都非常感激.

这是一个片段解释(通过评论)我想要的.

class Foo {
    constructor(bar) {
        // If someone else decides to create a new instance
        //  of 'Foo', then 'this.bar' should not set itself again.
        // I realize an instanced constructor is not correct.
        // In C#, I'd solve this by creating a static class, making
        //  'bar' a static property on the class.
        this.bar = bar;
    }
}
Run Code Online (Sandbox Code Playgroud)

ale*_*ods 5

我想这就是你想要的:

var instance = null;

class Foo {
  constructor(bar) {
    if (instance) {
      throw new Error('Foo already has an instance!!!');
    }
    instance = this;

    this.bar = bar;
  }
}
Run Code Online (Sandbox Code Playgroud)

要么

class Foo {
  constructor(bar) {
    if (Foo._instance) {
      throw new Error('Foo already has an instance!!!');
    }
    Foo._instance = this;

    this.bar = bar;
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 如果OP担心"某人"创建第二个实例,那么"某人"可以做很多事情...... ;-) (3认同)