Only allowing one instance of a class member in javascript

人走茶凉 提交于 2021-01-29 07:38:37

问题


I am creating a helper class in front of the google map API - just for the sake of learning.

I'd like to keep only one instance of the google.maps.Map object around in my class, even if someone decides to instantiate another instance of the class.

I'm coming from a .NET background, and the concept is simple there - however I'm still getting acclimated to javascript (and ES6), so any pointers are much appreciated.

Here's a snippet sort of explaining (through comments) what I'm going for.

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;
    }
}

回答1:


I think this is what you want:

var instance = null;

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

    this.bar = bar;
  }
}

or

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

    this.bar = bar;
  }
}


来源:https://stackoverflow.com/questions/33335872/only-allowing-one-instance-of-a-class-member-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!