LoginSignup
115
130

More than 5 years have passed since last update.

【jQuery】よく見るおまじない的なアレについて

Last updated at Posted at 2014-05-25

##「おまじない」のパターン
例えばこれらのような形式が挙げられると思う。

sample_1.html
<body>
<script>
// (1)
$(document).ready(function(){
    console.log($('#sample').text());
});
</script>
<div id="sample">foo</div>
</body>
sample_2.html
<body>
<script>
// (2)
$(function(){
    console.log($('#sample').text());
});
</script>
<div id="sample">foo</div>
</body>
sample_3.html
<body>
<script>
// (3)
(function($){
    console.log($('#sample').text());
})(jQuery);
</script>
<div id="sample">foo</div>
</body>

##これらは動作的に異なるものなのか?
結論から言えば、(1)と(2)は動作的に同じものであるが、(3)は違う。

(1)ではDOMがロードされ、操作可能になったタイミングでコールバック関数を実行する。そのためconsole.logで'foo'が正しく出力される。

また、(2)は(1)の$(document).ready()と同様に振る舞う関数jQuery(callback)であるため、こちらも'foo'が正常に出力されることになる。

一方で、(3)はjQueryオブジェクトを引数として渡している単なる即時関数である。
この記述は、「$というエイリアスが他のライブラリと衝突することを防ぐ」、「変数や関数のスコープを即時関数内に抑える」といった目的のために使用されており、スクリプトの実行タイミングを操作するものではない。
したがって<div id="sample">foo</div>がロードされる前にスクリプトが実行されるため、前に示した2つの例とは異なり、'foo'を出力することはできない。

##おまけ
なお、jQuery(callback)のドキュメントにも記載されているように、以下のような書き方をすれば$エイリアスの衝突も防ぐことができる。

jQuery(function($){
    console.log($('#sample').text());
});
115
130
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
115
130