gpt4 book ai didi

javascript - 如何知道类的实例是否来自单例?

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:56:31 25 4
gpt4 key购买 nike

我必须评估一个类的实例是否来自单例

我知道在 JavaScript 中要创建一个单例,我需要在构造函数中保存一个保存 this 的变量 instance(名称可以是任何名称)。

class Singleton {
constructor() {
const instance = this.constructor.instance;
if (instance) return instance;
this.constructor.instance = this;
}
}

但是如果我没有那个代码,我只是取回类的实例,例如:

let singletonOrMaybeNo = new Singleton()

我只有singletonOrMaybeNo

我如何知道该实例是单例还是否?

谢谢!!

最佳答案

您可以检查具有相同构造函数的实例的相同标识。

class Singleton {
constructor() {
const instance = this.constructor.instance;
if (instance) return instance;
this.constructor.instance = this;
}
}

class NoSingleton {
constructor() {
}
}


let singletonOrMaybeNo = new Singleton,
other = new NoSingleton;

// works only with known constructor
console.log(singletonOrMaybeNo === new Singleton);

// takes the constructor from the instance (kudos to Jonas Wilms)
console.log(singletonOrMaybeNo === new singletonOrMaybeNo.constructor);

console.log(other === new other.constructor);

关于javascript - 如何知道类的实例是否来自单例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56989470/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com