javascript - 在函数外的 Javascript 脚本中使用 "return"关键字

标签 javascript node.js browser ecmascript-6

return有什么用Javascript 脚本中的关键字,在函数之外,在浏览器和 Node 中?

我试过在 Node 脚本中使用它,如下所示:

#!/usr/bin/env node

return 10;

我的期望是这将使进程的返回状态等于 10 .然而,在询问在 bash 下运行的最后一个实用程序的返回状态时, 通过 echo $? , 我会收到 0 , 所以事实并非如此。

这引起了我对其他功能的好奇 return除了终止执行之外,在 Node 模块中间执行。另外,我想知道在浏览器的上下文中会发生什么 <script>

谢谢。

最佳答案

This woke my curiosity upon what else does returning in the middle of a Node module, apart from terminating execution, does.

当您使用 node.js 运行 Javascript 脚本文件时,它被包装在模块包装器函数中,如您所见 here in the node.js docs for Modules .

(function (exports, require, module, __filename, __dirname) {
     // Your module code actually lives in here
});

所以,你的 return是该模块包装器函数的返回,它除了停止执行该模块中的任何其他代码外什么都不做。 node.js 中的模块没有任何记录的从模块返回值的行为。所以,return;return 10;或者没有 return值,都具有相同的行为。不使用返回值。

与往常一样,在 Javascript 函数中,您可以使用普通的 return跳过模块中其余代码的执行,尽管最好只使用 if/else 来更清楚地只执行您要执行的代码。

My expectation was that this would make the return status of the process be equal to 10. However, upon asking the return status of the last utility ran under bash, by echo $?, I would receive 0, so that is not the case.

如果你想为进程设置一个返回值,你应该使用:

process.exit(10);

在 Node 模块中,如果想与其他模块共享数据,可以使用module.exports = some object or value ,但这对主模块没有影响,因为 Node 加载器没有关注 module.exports 的返回值。从主模块。这仅对您明确 require() 的其他模块有用中。

Also, I wonder what happens in the context of browser <script>s.

使用 return全局级别的声明(这是浏览器的顶层 <script> 语言不允许的标记。return 仅适用于函数内部。这样做会产生此错误:

Uncaught SyntaxError: Illegal return statement

关于javascript - 在函数外的 Javascript 脚本中使用 "return"关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42988291/

相关文章:

java - 在 Java 小程序运行失败时执行 JavaScript

node.js - 错误 : Virtual path "password" conflicts with a real path in the schema

node.js - 使用 ionic start 时找不到模块 'read'

css - Sailsjs 在 EJS 模板中没有 CSS

javascript - 为什么我不能在浏览器 : You may not have the required environment or OS to run this project 中运行空白的 Cordova 应用程序

java - HttpClient 重定向结果在浏览器中不可见

javascript - 多个阅读更多按钮不起作用?

javascript - 如何在 Angularjs 中使用 document.getElementById() 方法

javascript - 将动态字段添加到 Uploadify

javascript - 自调用函数javascript