1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

CommonJSでシングルトンっぽい実装

Last updated at Posted at 2016-02-14

コンストラクタパターンで1度しかnew演算子を使いたくない場合に便利です。
以下はcoffeescriptでの記述ですが素のjavascriptでも問題ないです。

クラス側

Hoge.coffee
class Hoge
  constructor: ->
    console.log 'test'

instance = undefined

getInstance = ->
  if not instance
    instance = new Hoge()
  instance

module.exports = getInstance

使い方

Main.coffee
class Main
  constructor: ->
    Hoge = require('./Hoge.coffee')()

$ ->
  new Main()  
1
1
3

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?