LoginSignup
37
29

More than 5 years have passed since last update.

JavaScriptで手軽にシングルトンをつくる【ES2015】

Last updated at Posted at 2018-03-08

JavaScriptのclassにはprivateがない。そのためJavaのようなシングルトンは作れないと思っていたが、実は簡単にシングルトンを作れることを知ったので共有。

オブジェクトをexportする

下のコードのようなSingletonクラスがあったとする。Singletonクラスは内部にメンバ変数xを持っており、メソッドgetX()が呼ばれるたびにインクリメントされる。

Singleton.jsではSingletonクラスのインスタンスをexportしている。これによりimportした場合、一つのインスタンスが共有されるようになる。

Singleton.js
class Singleton {
  constructor() {
    this.x = 0;
  }

  getX() {
    this.x++;
    console.log(this.x);
  }
}

export default new Singleton();

下のbridge.jsとmain.jsではSingleton.jsをimportしている。

bridge.jsはSingleton.getX()を呼ぶ関数をexportする。main.jsではSingleton.getX()とbridge.jsでexportされた関数をそれぞれ実行する。

bridge.js
import Singleton from './Singleton';

export default function() {
  Singleton.getX();
}
main.js
import Singleton from './Singleton';
import bridge from './bridge';

Singleton.getX();
bridge();

実行結果は以下の通り。1,2が出力され実行したどちらの関数も同じインスタンスを指していることがわかる。便利便利。

% ./node_modules/.bin/babel-node main.js
1
2
37
29
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
37
29