関数単位でスコープが決まる性質を利用する。
- 即時関数を使ってローカルスコープ化することにより、グローバル汚染を防ぐ。
- strictモードでは関数内のthisがundefinedになるため、callメソッドを使用する。
- 関数前の「;」はファイル連結時に不具合が出ないようにするための予防策。
<!DOCTYPE html>
<html>
<head lang="ja">
<meta charset="UTF-8">
<title>即時関数によるスコープ閉じ込め</title>
</head>
<body>
<ul>
<li id="first">1行目</li>
<li id="second">2行目</li>
<li id="third">3行目</li>
<ul>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.7.0/underscore-min.js"></script>
<script src="./js/app.js"></script>
</body>
</html>
;(function ($) {
'use strict';
alert('outside ready method: this = ' + this);
alert('outside ready method: $ = ' + $);
alert('outside ready method: _.VERSION = ' + _.VERSION);
$(function () {
alert('inside ready method: this = ' + this);
alert('inside ready method: $ = ' + $);
alert('inside ready method: _.VERSION = ' + _.VERSION);
$('#third').css('color', 'red');
});
alert('this = ' + this);
alert('$ = ' + $);
alert(_.VERSION);
}).call(this, jQuery);
//}.bind(this)(jQuery));
[参考URL]
知ってて当然?初級者のためのJavaScriptで使う即時関数(function(){...})()の全て - 三等兵
callで関数を即時実行すると何が嬉しいのか(と、ちょっとおまけ) - ただぱそこんしてるだけ
便利なjavascriptテクニック集 - Thujikun blog
"use strict" - blog.niw.at