为什么返回类型相同但结果不同

sur*_*ira 5 javascript console console.log

我在java脚本中有两个相同返回类型的函数但返回类型不同.下面使用snipped id的代码

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

    function foo2()
    {
      return
      {
          bar: "hello"
      };
    }
Run Code Online (Sandbox Code Playgroud)

调用函数..

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

输出结果....

foo1 returns:
Object {bar: "hello"}
foo2 returns:
undefined 
Run Code Online (Sandbox Code Playgroud)

Nin*_*olz 7

它在这里自动插入分号。其余的代码永远不会到达。

function foo2()
{
  return    // get a automatic semicolon insert here
  {
      bar: "hello"
  };
}
Run Code Online (Sandbox Code Playgroud)

请看一看:警告:返回语句后无法访问代码


fre*_*ish 5

那是因为JavaScript会解释

return
{
    bar: "hello"
};
Run Code Online (Sandbox Code Playgroud)

作为return语句,然后创建块(在运行时将其忽略)。不作为“返回对象”。而且我真的不知道为什么JavaScript开发人员会做出这样的决定。

无论如何,ASI会;return产生等效代码后插入:

return;
{
    bar: "hello"
};
Run Code Online (Sandbox Code Playgroud)

后面的换行符return是元凶。如果您想退货,请不要使用它。