简体   繁体   中英

Only allowing one instance of a class member in javascript

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM