簡體   English   中英

在JavaScript中僅允許類成員的一個實例

[英]Only allowing one instance of a class member in javascript

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM