javascript - javascript 中只允许类成员的一个实例

标签 javascript ecmascript-6

我正在 google map 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;
    }
}

最佳答案

我想这就是你想要的:

var instance = null;

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

    this.bar = bar;
  }
}

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

    this.bar = bar;
  }
}

关于javascript - javascript 中只允许类成员的一个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33335872/

相关文章:

javascript - 选择整个字典的值

ecmascript-6 - REPL 支持 babel-node es6 "Modules aren' t"

javascript - 概括类型化 setter 和 getter 的最佳方法是什么?

javascript - 如何在字典末尾追加键值对?

javascript - 删除 HTML 元素上的事件

javascript - 使用 codeigniter 创建数组输出(json)

javascript - 使用 ES6 简写符号进行调试 - 过滤器、映射、拒绝或减少

JavaScript 后退按钮事件

javascript "this"关键字在浏览器中按预期工作但在 node.js 中不工作

javascript - 如何使用 'this' 关键字规避 ES6 类范围问题