只允许javascript中的类成员的一个实例 [英] Only allowing one instance of a class member in javascript
本文介绍了只允许javascript中的类成员的一个实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在google map API的前面创建一个帮助器类-只是为了学习.
I am creating a helper class in front of the google map API - just for the sake of learning.
即使某人决定实例化该类的另一个实例,我也只希望在我的类中保留google.maps.Map对象的一个实例.
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.
我来自.NET背景,那里的概念很简单-但是我仍然适应javascript(和ES6),因此非常感谢任何指针.
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;
}
}
推荐答案
我认为这是您想要的:
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中的类成员的一个实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文