我正在 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;
}
}
关于javascript - javascript 中只允许类成员的一个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33335872/