Immediately-Invoked Function Expression (IIFE) In JavaScript - Passing jQuery

梦想的初衷 提交于 2019-11-27 15:39:00

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

Think of it like this:

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);

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.

$ 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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!