jQuery $(function(){})vs(function(){})($) [英] jQuery $(function() {}) vs (function () {})($)

查看:69
本文介绍了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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆