1
0

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.

関数内のスコープに保持された変数を参照、処理する関数

例1

関数内の値を +1 して返す。

const incrementAfterUse = (initNum)  => {
  let n = initNum;

  const increment = () => n++;

  return increment;
}

count = incrementAfterUse(1);
console.log(count()); // 1
console.log(count()); // 2
console.log(count()); // 3
console.log(count()); // 4

例2

const incrementFn = (initNum)  => {
  let n = initNum;

  return {
    increment: () => ++n,
    showNum: () => n
  }
}

let count = incrementFn(1);
console.log(count.showNum()); // 1
console.log(count.showNum()); // 1
console.log(count.increment()); // 2
console.log(count.increment()); // 3
console.log(count.showNum()); // 3
console.log(count.showNum()); // 3

個人的なイメージ

クラスのインスタンス変数、インスタンスメソッドみたいなことを関数でやるためのもののように見える。

その他、こんな感じの使い方もありますみたいなものがあれば教えてもらえると嬉しいです。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?