立即调用函数表达式(IIFE)在JavaScript中 - 传递jQuery [英] Immediately-Invoked Function Expression (IIFE) In JavaScript - Passing jQuery

查看:129
本文介绍了立即调用函数表达式(IIFE)在JavaScript中 - 传递jQuery的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码,我知道这是一个IIFE。但是,我从来没有能够掌握(jQuery)和($)是什么。我知道这与将jQuery的引用传递给IIFE有关,但有人可以清楚地向我解释它们的用途吗?谢谢你的帮助和时间: - )

I've got the following code which I know is an IIFE. However, I've never been able to grasp what the (jQuery) and ($) is. I know it's got something to do with passing a reference of jQuery into the IIFE, but could someone explain me clearly the purpose of them? Thank you for you help and time :-)

(function ($) {
//code
})(jQuery);


推荐答案

$ 是函数的参数。 jQuery 是在调用函数时作为该参数传递的内容。

$ is an argument to a function. jQuery is what is being passed as that argument when the function is invoked.

可以这样想:

function init($) {
   // code can use $ here as a shortcut for jQuery
   // even if $ has a different definition globally or isn't defined globally
}

init(jQuery);

除了此示例创建全局符号 init ,这和你的IIFE的执行完全相同。两者都定义了一个函数并立即调用它。

Except for the fact that this example creates a global symbol init, the execution of this and your IIFE are identical. Both define a function and immediately call it.

$ 是函数的参数。 jQuery 是作为该参数传递的内容。这用于定义 $ 作为 jQuery 的快捷方式,而不会影响<$ c $的全局定义C> $ 。有时也会有轻微的性能优势,因为本地定义的符号(作为局部变量或命名参数)可以比全局符号稍微快一些。

$ is an argument to the function. jQuery is what is passed as that argument. This serves to define $ as a shortcut for jQuery while inside that function without affecting the global definition of $. There can also sometimes be a slight performance advantage because symbols defined locally (either as local variables or as named arguments) can be slightly faster to access than global symbols.

优势IIFE的意思是没有定义新的全局符号。除此之外,它与此代码的执行完全相同。

The advantage of the IIFE is that no new global symbols are defined. Other than that, it's identical in execution to this code.

这篇关于立即调用函数表达式(IIFE)在JavaScript中 - 传递jQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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