jQuery 中的匿名函数语法

Anonymous functions syntax in jQuery

我阅读了很多关于 jQuery 及其语法的文章。但是我还没有完全理解它的语法,我真的很想对它有更好更深入的了解。

许多文章未能指出简单的语法规则(以及它们的必要性)。

截至目前,我遇到语法理解问题:

我的HTML:

<body>
    <a href="http://www.jquery.com" title="anchor1">jQuery.com</a>
    <a href="http://www.jquery.com" title="anchor2">jQuery.com</a>
    <a href="http://www.jquery.com" title="anchor3">jQuery.com</a>

    <!-- JQUERY -->
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

    <script>
        (function ($) {
            // EXAMPLE 1
            $("a").each(function () {
                console.log(this.title);
            });
        })(jQuery);                      // ... everything works fine.


        (function ($) {
            // EXAMPLE 2
            $("a").each(function () {
                console.log(this.title);
            });
        });           // ... missing (jQuery). Why isn't this working?


        $(function () {  // ... notice the $ at the beginning.
            // EXAMPLE 3
            $("a").each(function () {
                console.log(this.title);
            });
        });           // ... missing (jQuery). Why IS this working?


            // EXAMPLE 4
            $("a").each(function () {
              console.log(this.title);
            });                          // ... everything works fine.
    </script>
</body>  

我将阐明我是如何理解代码的,如果您能以非常基本的方式回答我,我将不胜感激。请务必指出我所有的误解!

目前我的理解和问题:
示例 1: 我创建了一个匿名 JavaScript 函数。该函数在浏览器读取它的那一刻立即执行。我将 jQuery-Object 传递给它(带有 ($),但我不知道为什么这在那个时候很重要)。从现在开始我的函数 'speaks' jQuery (它理解它的语法 - 我假设)。在我的 JavaScript 函数的最后,我再次将 jQuery 对象传递给它(但为什么这是必要的?)。请赐教。

示例 2: 我尝试了相同的函数但末尾没有 (jQuery)。现在它不起作用。我知道缺少什么。但为什么最后的 (jQuery) 如此重要?

示例 3: 现在我用 $ 开始了我的 Javascript-函数,我假设从现在开始我的整个函数都被包装在 [=56= 中] 目的。在这个 jQuery-object 中,我的函数理解 jQuery 语法。最后需要NO(jQuery)。

示例 4: 这里我没有构建 JavaScript 函数。我只是用jQuery到select和return("a")。这段代码在浏览器读取它的那一秒立即执行。无需等待文档准备就绪。

我的问题基本上是:
在示例 1 中,为什么开头的 ($) 和结尾的 (jQuery) 是必要的?目的是什么?

我真的很感激更长的答案,这样我可以更深入地了解 "reading jQuery syntax correctly" 并谈论 jQuery 语法及其要求。谢谢

您的问题的解决方案归结为了解 JavaScript 中的闭包......而不是 jQuery - jQuery 只是使用闭包。

使用闭包,您可以确定其中内容的范围,并将参数传递给该闭包以供在其中使用。

对于您的示例 2,如果您将 jQuery 传递给闭包,它将正常工作。 喜欢:

(function ($) 
{
  $("a").each(function () {
    console.log(this.title);
  });
})(jQuery); // arguments passed in here

因为你没有在最后传入jQuery,所以参数$是未定义的,因此在$('a')的情况下不能被调用。当按照我更改的方式编写时,它 jQuery 被分配给 $ 参数,它可用于闭包内的代码。

与您的示例 3 类似,您没有传入 jQuery,并且您的闭包中也没有变量 $,因此它不会起作用。请注意,您可以将其更改为(仅用于说明目的):

(function (thisIsJquery) 
{
  thisIsJquery("a").each(function () {
    console.log(this.title);
  });
})(jQuery);

现在 jQuery 被分配给参数 thisIsJquery 并且它在闭包中可用。

至于你的例子 4,$ 是在它定义的闭包中使用的(而不是里面的另一个闭包),所以它很容易使用。

闭包是隐藏实现的绝佳方式,并提供了一种在 JavaScript.

中实现 private 的方法

进一步阅读:

http://www.w3schools.com/js/js_function_closures.asp

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures

我只会关注不起作用的部分。以下片段:

(function ($) {               
   $("a").each(function () {
     console.log(this.title);
   });
}) // not calling function

首先,您没有调用该函数。所以,它里面的任何东西都不会运行。因此,您可能认为通过最后添加 () 可能会解决问题。

但这还不是全部!

因为 $ 在代码段之外引用 jQuery。但是由于您将命名参数包含为 $ 并且 未向其传递任何内容 ,因此代码段内的 $ 会遮蔽外部的参数。由于它没有分配任何值,因此它是 undefined。所以你最终会得到

undefined is not a function

为了证明这一点,添加 ($) 将起作用,因为现在,命名参数 $ 指的是指向 jQuery.[=21= 的 $ ]

首先,没有 "jQuery syntax"。 jQuery是一个库,写在JavaScript,所以语法是JavaScript.

Example 1: I create an anonymous JavaScript-function. This function is executed right in that moment the browser reads it. I pass it the jQuery-Object (with ($) but I don't know why this is important at that point). From now on my function 'speaks' jQuery (it understands its syntax - I am assuming). At the very end of my JavaScript-function I pass it the jQuery object again (but why would that be necessary?). Please enlighten me.

您似乎知道函数和参数的工作原理。所以看看你的代码:

(function ($) {
        // EXAMPLE 1
        $("a").each(function () {
            console.log(this.title);
        });
    })(jQuery);

您定义了一个接受一个参数的匿名函数:一个名为 $ 的变量,您在语句 $("a") 中使用了该变量。然后你调用你的匿名函数并将它传递给 jQuery 对象,所以在函数内部,$ === jQuery.

Example 2: I tried the same function without the (jQuery) at the end. Now it is not working. I understand what is missing. But why is that (jQuery) at the end so important?

  1. 最后没有 (),您甚至都没有调用您的函数。您只需定义它然后丢失它,因为您没有将它分配给变量。
  2. 如果你只输入 (),它也不会工作,因为函数参数 $ 将是未定义的并覆盖全局 $ (window.$)。

但是,如果您将函数声明为 function(),我认为它会起作用,因为 $ 将引用 window.$

Example 3: Now I STARTED my Javascript-function with the $ and I assume that from now on my whole function is WRAPPED inside a jQuery object. Inside this jQuery-object my function understands jQuery syntax. At the end NO (jQuery) is needed.

现在您将 $ 作为一个函数调用并带有一个参数:您的匿名函数。

Example 4: Here I did NOT build a JavaScript function. I just use jQuery to select and return the ("a"). This code gets executed right in the second the browser reads it. No waiting for the document to be ready.

是的,您确实构建了一个函数,并将其作为参数传递给 $("a") returns.

对象的 each() 函数

My Question basically is:
In Example 1, why is that ($) at the beginning AND the (jQuery) at the end necessary? What is the purpose?

函数参数的用途是什么?

但是你似乎不明白的是:$只是一个变量(也可以是一个函数,但在JS函数中变量)。

I create an anonymous JavaScript-function. This function is executed right in that moment the browser reads it.

不完全是。您创建一个函数表达式。

function () { }

然后用 () 跟随它,稍后调用它。

你可以这样做:

var myfunction = function ($) { ... };
myfunction(jQuery);

I pass it the jQuery-Object (with ($) but I don't know why this is important at that point).

没有。您正在定义一个函数。它接受一个参数,该参数的值被分配给一个名为 $.

的局部变量

From now on my function 'speaks' jQuery (it understands its syntax - I am assuming).

语法属于 JavaScript,而非 jQuery。

At the very end of my JavaScript-function I pass it the jQuery object again (but why would that be necessary?). Please enlighten me.

您是第一次传递 jQuery 对象。它是您在调用函数时传递给函数的参数。 jQuery(jQuery 对象)的值被分配给本地 $ 变量。

这有两个用途:

  1. 它让你可以使用 $ 变量而不用担心它会被 Prototype JS、Mootools 或任何其他认为使用像 [=13 这样通用的东西是个好主意的库覆盖=]作为变量名。
  2. 它让你拥有不会污染全局范围的局部变量。

I tried the same function without the (jQuery) at the end. Now it is not working. I understand what is missing. But why is that (jQuery) at the end so important?

() 很重要,因为没有它们您将无法调用函数。

jQuery 很重要,否则 $ 在函数中将是 undefined


Now I STARTED my Javascript-function with the $

此处您正在调用函数 $() 并将您的函数表达式作为参数。

$ 是一个可怕的重载函数,它根据你传递给它的参数类型做很多不同的事情。

如果您向它传递一个函数,那么它将将该函数分配为一个文档 ready 事件处理程序。

当 DOM 完成加载时,将触发事件并调用函数。


Here I did NOT build a JavaScript function. I just use jQuery to select and return the ("a"). This code gets executed right in the second the browser reads it. No waiting for the document to be ready.