LoginSignup
0
0

More than 3 years have passed since last update.

JavascriptでSingletonを実現する方法

Posted at

function Singleton () {
// すでにSingleton.instance が存在する場合にはSingleton.instance を返す
if(typeof Singleton.instance === 'object') {
return Singleton.instance;
}

// Singleton.instance は自身を参照する。
Singleton.instance = this;

return this;
}

var obj1 = new Singleton(); // new を使ってSingletonオブジェクトを作成する
var obj2 = new Singleton(); // new を使ってSingletonオブジェクトを作成する
console.log(obj1 === obj2); // true 2つは同じオブジェクト

0
0
0

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
0
0