LoginSignup
0
0

More than 1 year has passed since last update.

40代おっさんJavaScriptの即時関数を学ぶ

Posted at

本記事ついて

本記事は プログラミング初学者の私が学習していく中でわからない単語や概要をなるべくわかりやすい様にまとめたものです。
もし誤りなどありましたらコメントにてお知らせいただけるとありがたいです。

即時関数の使い方

関数の中で使える変数や、関数を区別するために使う

let c = (function() {

    console.log('called');
    let privateval = 0;
    let publicval = 10;

    function privateFn() {
        console.log('privateFn is called');
    }
    function publicFn() {
        console.log('publicFn is called');
    }

    return {
        publicval,
        publicFn
    };
})();

c.publicFn();

console.log(c.publicval);

こうするとpublicval,publicFnは関数の外で呼び出すことができますが
privateval,privateFnは呼び出せなくなり関数内でしか使えなくなります

例えば

let c = (function() {

    console.log('called');
    let privateval = 0;
    let publicval = 10;

    function privateFn() {
        console.log('privateFn is called');
    }
    function publicFn() {
        console.log('publicFn is called' + privateval++);
    }

    return {
        publicval,
        publicFn
    };
})();

c.publicFn();
c.publicFn();
c.publicFn();
c.publicFn();
c.publicFn();

console.log(c.publicval);

初期化は最初に呼ばれたときにしかしないのでその後は++する形になって表させることになる

参考資料

https://www.udemy.com/course/javascript-essence/

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