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

A.V*_*ore 2 javascript return

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

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

console.log(foo1());
console.log(foo2());
Run Code Online (Sandbox Code Playgroud)

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

the*_*eye 9

自动分号插入

引用规范,

continue,break,return,throw,或yield令牌遇到和LineTerminator被下一个标记之前遇到,分号之后自动插入continue,break,return,throw,或yield令牌.

所以代码将变成这样

function foo2() {
    return;          // Note the `;` after `return`
    {
        bar: "hello"
    };
}
Run Code Online (Sandbox Code Playgroud)

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