JavaScript/jQuery 中括号中的代码块意味着什么?

发布于 2024-10-10 22:58:28 字数 705 浏览 1 评论 0原文

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

我见过很多具有以下语法的 jQuery 代码,但我不太明白它的含义。它显示在此答案此答案有关代码组织的问题。两者都讨论命名空间,所以我猜这就是它所实现的目的。

var foo = (function () {
    var someVar;

    function someFunc() {
        return true;
    }
})();

这是为了命名空间吗?它是如何工作的?有时最后一组括号中有一个名称(命名空间?),有时则没有。两者有什么区别?

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

I've seen a lot of jQuery code with the following sort of syntax, but I don't really understand what it means. It shows up in this answer and this answer on a question about code organization. Both talk about namespacing, so I'm guessing that's what it accomplishes.

var foo = (function () {
    var someVar;

    function someFunc() {
        return true;
    }
})();

Is this for namespacing, and how does it work? Sometimes there is a name (the namespace?) in the final set of parentheses, sometimes not. What is the difference between the two?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

樱娆 2024-10-17 22:58:28

包装函数的 () 将匿名函数声明转换为函数表达式,然后可以使用表达式后面的 () 立即调用该函数表达式。

在这种情况下,外部 () 实际上是不必要的,因为 var foo = 会将其转换为表达式。此外,由于函数调用不返回任何内容,因此 foo 的值将为 undefined

它可用于创建新的变量范围,因为函数是在 javascript 中完成此操作的唯一方法。 (Javascript 没有块作用域。)

因此外部作用域无法访问 someVar 变量。有时可能需要以受控方式对其进行访问。为此,您可以将引用 someVar 的函数传递到该范围之外。然后,在函数调用退出后,其执行上下文将保持不变,并且 someVar 将以您传递的函数提供的任何方式可用。

这称为创建闭包

假设您将一个值传递到调用中,并将其分配给 someVar。然后,您可以从对 foo 变量的调用中返回一个函数。如果该函数返回引用 someVar,那么您可以使用该函数来获取其值。

var foo = (function ( str ) {
    var someVar = str;
/*
    function someFunc() {
        return true;
    }
*/
    return function() {
        alert( someVar );
    };
})( 'somevalue' );

foo(); // alerts 'somevalue'

如您所见,现在 foo 引用的函数仍然可以访问 someVar

假设您对其进行了更改,以便返回到 foo 的函数可以接受参数,这将更新 myVar 的值。

var foo = (function ( str ) {
    var someVar = str;
/*
    function someFunc() {
        return true;
    }
*/
    return function( n ) {
        if( n ) {
            someVar = n;
        } else {
            alert( someVar );
        }
    };
})( 'somevalue' );

foo(); // alerts 'somevalue'

foo( 'newvalue' ); // give it a new value

foo(); // alerts 'newvalue'

现在您可以看到,foo 中的函数确实访问了该变量,因为它能够更改其值,并引用之前设置的新值。

The () that wrap the function turns the anonymous function declaration into a function expression that can then be immediately invoked with the () that follows the expression.

In this case, the outer () really isn't necessary since the var foo = would turn it into an expression. Also, the value of foo will be undefined since the function invocation doesn't return anything.

It can be used for creating a new variable scope, since a function is the only way to accomplish that in javascript. (Javascript doesn't have block scope.)

So the someVar variable is not accessible to the outer scope. There may be times when it is desirable to make it accessible in a controlled manner. To do this, you can pass a function out of that scope which references someVar. Then after the function invocation exits, its execution context will remain intact, and someVar will be available in whatever manner the function you passed out provides.

This is called creating a closure.

Let's say you passed a value into the invocation, and assigned it to someVar. You could then return a function out of the invocation to the foo variable. If that function you return references someVar, then you could use that function to get its value.

var foo = (function ( str ) {
    var someVar = str;
/*
    function someFunc() {
        return true;
    }
*/
    return function() {
        alert( someVar );
    };
})( 'somevalue' );

foo(); // alerts 'somevalue'

As you can see, the function now referenced by foo can still access someVar.

Let's say you changed it so that the function returned to foo can accept an argument, which will update the value of myVar.

var foo = (function ( str ) {
    var someVar = str;
/*
    function someFunc() {
        return true;
    }
*/
    return function( n ) {
        if( n ) {
            someVar = n;
        } else {
            alert( someVar );
        }
    };
})( 'somevalue' );

foo(); // alerts 'somevalue'

foo( 'newvalue' ); // give it a new value

foo(); // alerts 'newvalue'

Now you can see, that the function in foo really does access that variable, as it is able to change its value, and reference the new value that it previously set.

听,心雨的声音 2024-10-17 22:58:28

括号括住匿名函数,以便使其成为可以通过在其后面添加参数直接调用的变量。

(function(param) {
    // do stuff
})(param);

末尾的位不是命名空间,只是一个参数。您可能已经看到它用于 jQuery:

(function($) {
    $('.something').addClass('.other');
})(jQuery);

它的作用是将 jQuery 对象传递给函数,使 $ 变量成为匿名函数范围内的 jQuery 对象。人们喜欢使用简写 $,但它可能会导致与其他库的冲突。此技术通过传递完全限定的 jQuery 对象并覆盖该函数范围内的 $ 变量来消除冲突的可能性,因此可以使用快捷方式。

The parentheses wrap around an anonymous function, in order to make it a variable that can be called directly by adding the parameters after it.

(function(param) {
    // do stuff
})(param);

The bit at the end is not a namespace, just a parameter. You have probably seen this used for jQuery as:

(function($) {
    $('.something').addClass('.other');
})(jQuery);

What this does is pass the jQuery object in to the function, making the $ variable the jQuery object in within the scope of the anonymous function. People like to use the shorthand $, but it can lead to conflicts with other libraries. This technique removes the possibility of a conflict by passing the fully qualified jQuery object in and overwriting the $ variable within the scope of that function, so the shortcut can be used.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文