LoginSignup
4
3

More than 5 years have passed since last update.

関数の中にクラスを定義する

Last updated at Posted at 2018-04-24

先に書いておくと、読む必要のない記事です。
実行環境: node v9.11.1

関数を返す関数は高階関数として頻出するパターンでよく使われる。

function createCounter() {
  let count = 0
  return () => {
    count += 1
    return count
  }
}

const counter = createCounter()

console.log(counter())
// => 1
console.log(counter())
// => 2
console.log(counter())
// => 3

本題はここからで、関数の中にクラスを定義できる。

function createCounter2() {
  class Counter {
    constructor() {
      this.count = 0
    }
    add() {
      this.count += 1
    }
  }

  const counter = new Counter()

  return () => {
    counter.add()
    return counter.count
  }
}

const counter2 = createCounter2()

console.log(counter2())
// => 1
console.log(counter2())
// => 2
console.log(counter2())
// => 3

さらにデフォルト引数でクラスを定義できるので、もっと楽しくすることもできる。

function createCounter3(
  Counter = class {
    constructor() {
      this.count = 0
    }
    add() {
      this.count += 1
    }
  }
) {
  const counter = new Counter()

  return () => {
    counter.add()
    return counter.count
  }
}

const counter3 = createCounter3()

console.log(counter3())
// => 1
console.log(counter3())
// => 2
console.log(counter3())
// => 3

便利ですね。

さらにnew class{}()でインスタンス生成できるのでデフォルト引数ないで無名クラスのインスタンス化ができる。

function createCounter4(
  counter = new class {
    constructor() {
      this.count = 0
    }
    add() {
      this.count += 1
    }
  }()
) {
  return () => {
    counter.add()
    return counter.count
  }
}

const counter4 = createCounter4()

console.log(counter4())
// => 1
console.log(counter4())
// => 2
console.log(counter4())
// => 3

特にオチはありません。

4
3
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
4
3