为什么这些语法相同的函数产生不同的结果?

时间:2016-07-21 06:52:41

标签: javascript return

function foo1() {
    return {
        bar: "hello"
    };
}

function foo2() {
    return
    {
        bar: "hello"
    };
}

console.log(foo1());
console.log(foo2());

即使代码看起来相同,我能解释为什么这两个函数会打印出不同的结果吗?

1 个答案:

答案 0 :(得分:9)

自动分号插入

引用the specification

  

遇到continuebreakreturnthrowyield令牌且遇到 LineTerminator 时在下一个标记之前,会在continuebreakreturnthrowyield标记之后自动插入分号。

所以代码将变成这样

function foo2() {
    return;          // Note the `;` after `return`
    {
        bar: "hello"
    };
}

return语句终止,然后在那之后有一个对象,它基本上是无法访问的代码。由于return语句未明确返回任何内容,因此将返回undefined

相关问题