javascript nodejs 需要使用“严格使用”吗?或者 node 严格模式的最佳实践是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30634380/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
nodejs need use 'strict use'?or what is the best practice of node's strict mode?
提问by Edward
I'm a new to node.js and javascript.I checked code examples of node.js and it used use strict
mode.
我是 node.js 和 javascript 的新手。我检查了 node.js 的代码示例并使用了use strict
模式。
For example, a server.js:
例如,一个 server.js:
'use strict';
//some server code
Also, I got to know that use strict
is present at head of every js file.
It confused me and so I want to know what is best practice in Nodejs to use strict mode?
另外,我知道它use strict
存在于每个 js 文件的开头。这让我很困惑,所以我想知道 Nodejs 中使用严格模式的最佳实践是什么?
Thank you all, My question is focus on the strict mode. In this mode, some code mistake can be reported. In back-end, the strict error reporter also run? And If I need use it, I should add it in every js file header? Or add it in main file(server.js or etc.) head? Or use some node.js self style?
谢谢大家,我的问题是关注严格模式。在这种模式下,可以报告一些代码错误。在后端,严格的错误报告器也运行?如果我需要使用它,我应该在每个 js 文件头中添加它吗?或者将它添加到主文件(server.js 等)头中?或者使用一些 node.js 自己的风格?
采纳答案by Jeffrey A. Gochin
Use it always. If nothing else, it ensures that your code is properly written, and cross browser compatible as it can be. It also will reveal mundane syntax errors that would otherwise go unfound, and lead to hours of unnecessary debugging.
始终使用它。如果不出意外,它可以确保您的代码编写正确,并且尽可能兼容跨浏览器。它还将揭示原本不会被发现的普通语法错误,并导致数小时的不必要调试。
回答by Anand Sudhanaboina
“use strict” is a behavior flag you can add to to first line of any JavaScript file or function. It causes errors when certain bad practices are use in your code, and disallows the use of certain functions, such as with.
“use strict”是一个行为标志,您可以添加到任何 JavaScript 文件或函数的第一行。当您的代码中使用某些不良做法时,它会导致错误,并禁止使用某些功能,例如 with。
References:
参考:
回答by Saba Hassan
Nodejs is server-side javascript, so many coding practices are similar in both. So using strict mode is common.
Nodejs 是服务器端 javascript,因此两者的许多编码实践都是相似的。所以使用严格模式很常见。
It ensures that you are not violating certain coding conventions like undeclared variables x=14;
, use of specific variable names arguments,eval
which are names of few global variables and functions.
它确保您不会违反某些编码约定,例如未声明的变量x=14;
、使用特定变量名称(arguments,eval
即少数全局变量和函数的名称)。