javascript 即時関数を使用して実行結果を得る
- 2020.09.05
- javascript
- javascript

javascriptで即時関数の使い方と簡単な実行結果を得るサンプルコードを記述してます。
環境
- OS windows10 pro 64bit
- Apache 2.4.43
- ブラウザ chrome 84.0.4147.105
即時関数使い方
即時関数を使用すると、結果をすぐに得ることが可能です。
1 2 3 |
(function(){ //処理を記述 })(); |
即時関数使い方
1 2 3 4 5 |
var plus = (function (num1,num2){ return num1 + num2; })(100,200); console.log(plus); // 300 |
また、即時関数を利用すれば、グローバル変数の値を変更せずにグローバル変数を利用することができます。
1 2 3 4 5 6 7 8 |
var num = 5; (function(num){ num = num + 1; console.log(num); // 5 })(num); console.log(num); // 6 |
サンプルコード
以下は、即時関数を実行して、グローバル変数の値を表示するサンプルコードとなります。
※cssには「bootstrap material」を使用してます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="utf-8"> <title>mebeeサンプル</title> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Material+Icons"> <link rel="stylesheet" href="https://unpkg.com/bootstrap-material-design@4.1.1/dist/css/bootstrap-material-design.min.css" integrity="sha384-wXznGJNEXNG1NFsbm0ugrLFMQPWswR3lds2VeinahP8N0zJw9VWSopbjv2x7WCvX" crossorigin="anonymous"> </head> <style> .main { margin: 0 auto; margin-top: 150px; display: flex; flex-direction: column; align-items: center; font-size: 20px; } </style> <script> window.onload = function () { var x = 5; document.getElementById('val1').textContent = "即時関数実行前 : x = " + x; // 5 (function(x){ x = x + 1; document.getElementById('val2').textContent = "即時関数実行中 : x = " + x; // 5 })(x); document.getElementById('val3').textContent = "即時関数実行後 : x = " + x; // 6 } </script> <body> <div class="main"> <h5 id="val1"></h5> <h5 id="val2"></h5> <h5 id="val3"></h5> </div> </body> </html> |
即時関数を実行してもグローバル変数の値が変わらないことが確認できます。

-
前の記事
javascript checkbox全てをaddEventListenerに加える 2020.09.04
-
次の記事
javascript base64に日本語をエンコードする 2020.09.05
コメントを書く