LoginSignup
4
1

More than 5 years have passed since last update.

クロージャの便利なところを簡潔に記す

Last updated at Posted at 2018-07-24

基本、内部の無名関数を返す

hello.js

function outMethod () {

    return function () {
        console.log('hello');
    };
}

var fc = outMethod();
fc(); // hello

次のサンプルの内容はとても便利。いろいろ使いみちがありそう。
変数の中身を保持してくれるところが便利。
リロードするまで値を保持してくれる

変数の中身を保持して使える

count.js
function outMethod() {
    var x = 1;

    return function () {
        console.log(x);
        x = x + 1
    };
}

var fc = outMethod();
fc(); // 1
fc(); // 2
fc(); // 3

メモ

無名関数には、セミコロンをつける。
単純なものだとつけなくてもエラーにならないが、ネストするとどこまでが無名関数か分からずエラーになるらしい。

大変参考になりました。ありがとうございました。

[JavaScript] 猿でもわかるクロージャ超入門 5 クロージャを作る

中上級者になるためのJavaScript【知識編】

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