I know here the global jQuery is passed as $ to function, との違いは何ですか?
(function($){
})(jQuery);
そしてこれ
$(function(){
})();
I know here the global jQuery is passed as $ to function, との違いは何ですか?
(function($){
})(jQuery);
そしてこれ
$(function(){
})();
2 つ目のパターンは、誤って呼び出し括弧を含めない限り、一般的なパターンではありません (型エラーがスローされます)。
(function($){
// Normal IIFE that happens to pass jQuery in as an argument
})(jQuery);
$(function(){
// Shorthand DOM-ready event handler
}); // <-- Remove the invoking parentheses
$(function(){
});
これは、DOM 対応のイベント ハンドラーの単なる省略形であり、次と同等です。
$(document).ready(function(){
// execution when DOM is loaded...
});
これに移りましょう:
(function($){
// code here
})(jQuery);
このコードは DOM Ready では実行されませんが、直接実行されます。jQuery をパラメーターとして関数に渡す利点は、ドル記号 ( $) の使用法との衝突を回避することです。これは、複数のライブラリが省略形の参照として使用するためです。$これは への参照として渡されるため、関数内のすべてのものが を安全に使用できますjQuery。
シンボルの競合について詳しく読む$: jQuery noConflict
2 つのコード スニペットを組み合わせると、適切で堅実なセットアップが得られます。
// $ reference is unsafe here in the global scope if you use multiple libraries
(function($){
// $ is a reference to jQuery here, passed in as argument
$(function(){
// executed on dom-ready
});
})(jQuery);
PS : functionJavaScript では、コンテキストに応じてステートメントまたは式の両方になる可能性があるため、ほとんどの人はそれを強制的に式にするために余分な括弧を追加します。