javascript jQuery 的 function($) (jQuery) 语法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4531110/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 14:01:16  来源:igfitidea点击:

jQuery's function($) (jQuery) syntax

javascriptjqueryapi

提问by mehdi

Possible Duplicate:
jQuery: What does (function($) {})(jQuery); mean?

可能的重复:
jQuery: What do (function($) {})(jQuery); 意思是?

I stumbled up on the following code (included in one file) but I just cannot understand what it really means.

我偶然发现了以下代码(包含在一个文件中),但我无法理解它的真正含义。

(function ($) {
    function doSomething1(somedata) {

    }

    function doSomething1(somedata) {

    }
})(jQuery);

Question 1: What does this syntax mean in the contex of jQuery

问题 1:这个语法在 jQuery 的上下文中意味着什么

Question 2: How can we call these functions let say from other files such as the HTML index file and other JavaScript files?

问题 2:我们如何从其他文件(例如 HTML 索引文件和其他 JavaScript 文件)中调用这些函数?

Thanks

谢谢

回答by Nikita Rybak

This syntax is not particularly special to jquery, it's normal javascript. Here simply function

这种语法对于 jquery 来说并不是特别特殊,它是普通的 javascript。这里只是功能

function ($) {
    // some code here...
}

(note that it takes argument named $) is called with parameter jQuery(which is, obviously, global object of jQuery framework).

(请注意,它采用名为 的参数$)通过参数jQuery(显然,这是 jQuery 框架的全局对象)调用。

This is usually done when there're several js frameworks on one page (jquery, dojo, prototype, etc) which all redefine global variable $. But with this code, inside doSomething1or doSomething2you can always call $('.test')and be certain that call will be processed by jquery, not dojo. Because $is not a global variable in this case, it's function parameter.

这通常是在一个页面上有多个 js 框架(jquery、dojo、prototype 等)都重新定义全局变量时完成的$。但是使用此代码,在内部doSomething1doSomething2您始终可以调用$('.test')并确定调用将由 jquery 处理,而不是由 dojo 处理。因为$在这种情况下不是全局变量,它是函数参数。

回答by Mantar

I'm not sure about your question here, but the (function() means it's self-executing,

我不确定你的问题,但 (function() 表示它是自动执行的,

and you call them by importing the files in the main page and then calling

然后通过导入主页中的文件然后调用它们来调用它们

doSomething1()

做某事1()

回答by ifaour

Mostly likely that was jQuery plugin: Plugins/Authoring

很可能是 jQuery 插件:Plugins/Authoring