3
4

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.

クロージャー

Last updated at Posted at 2017-06-04

・variableは定義されたときにメモリに保存される
・functionは実行されたときに中をみる
・const とかletとかにfunctionが代入されている場合、そのfunctionにはいっている変数を別のメモリに保存し、その参照をそこに保存する
・functionが実行されたときにreturnをみる。

・参照型:object, array
・プリミティブ型:string, integer, float, boolean

sample.js
let countNumber = 0; // #0 = 0

// obejct array referece
// string integer float boolean primitive

const createCounter = () => {
  countNumber = countNumber + 1;
  const myNumber = countNumber; // #0(countNumber) = 2, #4(myNumber2) = 2
  let counter = 0 // #5(counter2) = 0

  const f = () => { // Capture: counter = #5, myNumber = #4
    counter++
    console.log(`Counter ${myNumber}: ${counter}`)
  }
  return f
}

let c1 = createCounter(); // myNumber: #1 counter: #2
let c2 = createCounter(); // myNumber: #4 counter: #5
let c3 = createCounter(); // myNumber: #7 counter: #8

c2()
c2()
c2()
c2()

c3();

c1();
c1();

closure.jpg

参考文献

関数を理解すればクロージャは難しくない!
http://analogic.jp/closure/

JavaScriptのクロージャは内部でどう機能するのか
http://postd.cc/how-do-javascript-closures-work-under-the-hood/

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?