这两个JavaScript声明有什么区别

这两个JavaScript声明有什么区别

本文介绍了这两个JavaScript声明有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于其中一个,()在里面,而另一个在外面。它们是:

For one of them the "()" is inside, for the other one it is outside. Here they are:

var a = (function() {
    return {
        bla: function() {
            console.log('a');
        }
    };
} () );

var b = (function() {
    return {
        bla: function() {
            console.log('b');
        }
    };
}) ();

a.bla();
b.bla();


推荐答案

没有区别。

[不必要]括号只是在不同的地方。函数声明已经是表达式,因为它位于何处。如果声明位于语句上下文(并且具有讽刺意味的是,它们会将其转换回表达式上下文),则括号会产生差异,同时仍会产生等效代码,它不是。

The [unnecessary] parenthesis are just in different places. The function declaration is already an expression due to where it is located. The parenthesis would make a difference, while still resulting in equivalent code, if the declaration was in a statement context (and ironically they would turn it back into an expression context), which it is not.

类似场景中括号的常见用法是自我 - 启动功能。在这种情况下需要括号,因为

The common use of parenthesis in a similar scenario is for self-invoking functions. The parenthesis are required in this case because

function x () { alert("hi!") } ()

被解析为

function x () { alert("hi!") }; ()

当它显示为语句 - 或顶级时块的元素 - 它被解析为FunctionDeclaration。因此,经常使用以下形式:

when it appears as a statement -- or "top level element of a block" -- where it is parsed as a "FunctionDeclaration". Thus the following form is often used:

(function () { alert("hi!") })()

这是因为函数... 不再一个语句,如上所述,但是一个表达式(解析为FunctionExpression),表达式可以继续,所以不会像前一种情况那样发生。另请注意,函数名称可以省略。

This works because function ... is no longer a statement, as above, but an expression (parsed as a "FunctionExpression"), and the expression can continue so the Automatic Semicolon Insertion does not occur as in the previous case. Also note that the function name can be omitted.

但是,因为在帖子中出现函数... = 的右侧中(在AssignmentExpression中),它已经在表达式上下文(被解析为FunctionExpression),因此不需要额外的括号。

However, because in the post the function ... appears in an on the right of an = (in an "AssignmentExpression") it is therefore already in an expression context (is parsed as a "FunctionExpression") and thus no additional parenthesis are needed.

所有这些都是相同,但我更喜欢第二种形式(为了在我的代码中保持一致):

All of these are identical, but I prefer the 2nd form (for consistency within my code):

a = function () {} ()
b = (function () {}) ()
c = (function () {} ())

快乐编码。

这篇关于这两个JavaScript声明有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 10:41