围绕对象/函数/类声明的括号是什么意思? [英] What do parentheses surrounding an object/function/class declaration mean?

查看:145
本文介绍了围绕对象/函数/类声明的括号是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是JavaScript和 YUI 的新手。在YUI库示例中,您可以找到此构造的许多用法:

I'm new to both JavaScript and YUI. In YUI library examples, you can find many uses of this construct:

(function() {
    var Dom = YAHOO.util.Dom,
    Event = YAHOO.util.Event,
    layout = null,
        ...
})();

我认为最后几个括号是在声明后立即执行该功能。

I think the last couple of parentheses are to execute the function just after the declaration.

...但是围绕函数声明的前一组括号怎么样?

... But what about the previous set of parentheses surrounding the function declaration?

我认为这是范围问题;这是将内部变量隐藏到外部函数和可能的全局对象中。是吗?更一般地说,这些括号的机制是什么?

I think it is a matter of scope; that's to hide inside variables to outside functions and possibly global objects. Is it? More generally, what are the mechanics of those parentheses?

推荐答案

这是一个自动执行的匿名函数。第一组括号包含要执行的表达式,第二组括号执行这些表达式。

It is a self-executing anonymous function. The first set of parentheses contain the expressions to be executed, and the second set of parentheses executes those expressions.

尝试隐藏父项中的变量时,它是一个有用的构造命名空间。函数中的所有代码都包含在函数的私有范围内,这意味着函数外部无法访问它,使其真正成为私有。

It is a useful construct when trying to hide variables from the parent namespace. All the code within the function is contained in the private scope of the function, meaning it can't be accessed at all from outside the function, making it truly private.

请参阅:

http:// en.wikipedia.org/wiki/Closure_%28computer_science%29

http://peter.michaux.ca/articles/javascript-namespacing

这篇关于围绕对象/函数/类声明的括号是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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