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

Only allowing one instance of a class member in javascript

本文关键字:成员 实例 许一个 javascript      更新时间:2023-09-26

我在google地图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;
  }
}