0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

即時関数について

Posted at

即時関数とはこういったもの

(function () {
  console.log('called.');
})();

即時間数の使い道

関数スコープを用いて、関数の中だけで使いたいものと、関数の外側で使いたいものを明確に区別するときに使う。

let c = (function () {
  console.log('called.');

  // private変数
  let privateVal = 0;
  // public変数
  let publicVal = 10;

  // private関数(外から呼び出せない)
  function privateFunc() {
    console.log('privateFunc is called.');
  }
  // public関数(外から呼び出せる)
  function publicFunc() {
    console.log('publicFunc is called.' + privateVal++);
  }

  privateFunc();

  // privateValとpublicFuncを外から呼び出せるようにする。
  return {
    // オブジェクトリテラル
    // 本来、変数: プロパティ名
    // だが、変数名とプロパティ名が同じ時はプロパティ名省略可能
    publicVal,
    publicFunc
  }
})();

c.publicFunc();
c.publicFunc();
c.publicFunc();
c.publicFunc();
console.log(c.publicVal);

参考

【JS】ガチで学びたい人のためのJavaScriptメカニズム

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?