在浏览 hapi 官方教程的时候,我注意到其中的范例只要在从 route 中接收参数的时候都使用 const 即常量来存放数值,最初对这个做法不太理解,因为用 let 或 var 来定义一个变量不是更好吗?为什么一定要用常量呢?
搜索后找到了答案,stackoverflow 上的一位程序员做出了解答:
There are two aspects to your questions: what are the technical aspects of using
const
instead ofvar
and what are the human-related aspects of doing so.The technical difference is significant. In compiled languages, a constant will be replaced at compile-time and its use will allow for other optimizations like dead code removal to further increase the runtime efficiency of the code. Recent (loosely used term) JavaScript engines actually compile JS code to get better performance, so using the const keyword would inform them that the optimizations described above are possible and should be done. This results in better performance.
The human-related aspect is about the semantics of the keyword. A variable is a data structure that contains information that is expected to change. A constant is a data structure that contains information that will never change. If there is room for error,
var
should always be used. However, not all information that never changes in the lifetime of a program needs to be declared withconst
. If under different circumstances the information should change, usevar
to indicate that, even if the actual change doesn't appear in your code.
https://stackoverflow.com/questions/21237105/const-in-javascript-when-to-use-it-and-is-it-necessary
大意是:现今的 js 代码在执行时大多会经过编译来提升效率,比如 node.js 这种借助 V8 引擎来运行的,在编译过程中声明为 const 的数值会得到更好的优化而速度更快,反之通过 let 和 var 定义的变量则不会。因此,当我们在编写代码时,如果能够预见某一类数值在后续的运行中是不会改变的,那就尽量将其标记为常量。所以,按照这个标准来判断的话,通过 route 传入的参数或用户在表单中输入的内容自然都符合这一条件了。