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

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

问题描述

我是 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天全站免登陆