我发现不同的主题解释了如何创建单例,但没有一个对我有用。这是取自这篇文章的例子
export default class Credentials {
static myInstance = null;
_userID = "";
static getInstance() {
if (myInstance == null) {
myInstance = new Credentials();
}
return myInstance;
}
getUserID() {
return this._userID;
}
setUserID(id) {
this._userID = id;
}
}
当我调用 Credentials.getInstance()
时,我收到警告
Can't find variable myInstance
最佳答案
JS 没有像静态编译语言那样的隐式字段查找。您需要明确地查找类上的变量:
class Credentials {
static myInstance = null;
static getInstance() {
if (Credentials.myInstance == null) {
Credentials.myInstance = new Credentials();
}
return Credentials.myInstance;
}
}
谨慎使用这种方法,因为它不是真正的单例,因为 JS 没有适当的类封装。
您可以轻松地直接更改实例:
Credentials.myInstance = 'something else';
正确的封装单例应该通过闭包来实现:
const Credentials = (() => {
let myInstance = null;
return class Credentials {
static getInstance() {
if (myInstance == null) {
myInstance = new Credentials();
}
return myInstance;
}
}
})()
关于javascript - 使用 React Native 创建单例类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47658423/