jQuery $(function(){})vs(function(){})($) [英] jQuery $(function() {}) vs (function () {})($)
问题描述
我了解以下是$( document ).ready()
的简写:
$(function() {
console.log( "ready!" );
});
我也了解什么是匿名JS函数,但是当使用jQuery函数调用时,jQuery会做些特殊的事情吗?即:
I also understand what an anonymous JS function is, but does jQuery does anything special when it's called using one. I.e.:
(function() {
console.log( "ready!" );
})($);
后者是否只是使用jQuery的普通匿名JS函数(即,它不会被视为$(document).ready()
的简写,因此将立即执行)?
Is the latter just a normal anonymous JS function that uses jQuery (ie. it will NOT be considered shorthand for $(document).ready()
and so will execute immediately)?
我认为必须先问过这个问题,但是如果有的话我找不到.
I feel this MUST have been asked before, but I can't find it if it has.
推荐答案
正如您提到的,前者确实是$(document).ready()
的简写.
对于后者,这只是一个立即调用的函数表达式.
As you mentioned, the former is indeed a shorthand for $(document).ready()
.
As for the latter, this is just an Immediately Invoked Function Expression.
(function ($) {
console.log('ready');
})(jQuery);
此函数只是一个匿名函数,它接收名为$
的参数.使用某些值(在本例中为jQuery
)作为参数立即调用.
This function is simply an anonymous function which receives a parameter named $
. The function is immediately invoked with some value (in this case jQuery
) as the parameter.
IIFE还可以用于在包含多个JavaScript文件的Web应用程序中隔离范围和避免全局变量.在这种情况下,可以使用无参数的IIFE:
IIFEs can also be used to isolate scopes and to avoid global variables in web applications which contain multiple JavaScript files. In this case a parameterless IIFE could be used:
(function () {
// x is only accessible within this IIFE
var x;
// do something...
})();
For more information regarding Immediately Invoked Function Expression, see this question: What is the purpose of a self executing function in javascript?
这篇关于jQuery $(function(){})vs(function(){})($)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!