使用react native创建一个单例类

时间:2017-12-05 16:34:56

标签: javascript react-native

我发现不同的主题解释了如何创建一个单例,但它们都不适合我。这是从这篇文章中取得的一个例子

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()时,我收到了警告

  

无法找到变量myInstance

3 个答案:

答案 0 :(得分:2)

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;
    } 
  }
})()

答案 1 :(得分:0)

我认为最干净,最简单的解决方案是“ES6单例模式”(不确定该模式是否有正式名称)。

您将实例导出为默认值,并且在导入它的任何位置都会获得相同的实例。这依赖于模块需要被缓存的事实。

你会创建你的类并导出类似的东西:

class Credentials {

    constructor() {
        this._userID = "";
    }

    get userID() {
        return this._userID;
    }

    set userID(userID) {
        this._userID = userID;
    }

}

export default new Credentials();

无论您在何处导入,都会获得相同的实例:

import credentials from './credentials';

答案 2 :(得分:0)

对于JS中的任何类型的单吨实例,这应该足够了。

现在,无论您在何处导入,都将使用相同的实例。您可以通过在类中添加日期并在导入它的各个位置访问它来进行交叉检查。

import { SomeClass } from 'some-class'

let singletonInstance;

if (!singletonInstance) {
  singletonInstance = new SomeClass();
  // singletonInstance.time = new Date();
}

export default singletonInstance;

然后使用

导入它

import singletonInstance from './above-code-file'