const vs let调用require时 [英] const vs let when calling require
问题描述
由于io.js现在支持ES6 ,您终于可以使用 const
和 let
关键字。显然, let
是 var
的继承者,只是一些超级大国。
As io.js now supports ES6 you are finally able to use the const
and let
keywords. Obviously, let
is the successor of var
, just with some super-powers.
但是, const
呢?我知道,当然,不变是什么意思,但是我想知道什么时候使用它(关于最佳做法)。
But what about const
? I know, of course, what "constant" means, but I was wondering when to use it (regarding best practices).
例如,如果我创建一个需要的模块另一个模块,我可以写:
E.g., if I create a module that requires another module, I could write:
'use strict';
const util = require('util');
const foo = function () {
// Do something with util
};
module.exports = foo;
基本上我已经替换了每一次 var
与 const
。一般来说,我认为这是可以的,但是如果我遵循这种模式,它会使我更多地使用 const
比 let
,因为大多数变量不是字面意义上的变量。
Basically I've replaced every occurence of var
with const
. Generally speaking, I think that this is okay, but if I follow this pattern, it leaves me with way more uses of const
than let
, as most variables aren't "variables" in a literal sense.
这种风格好吗?我宁愿去让
?什么时候应该选择 const
over let
?
Is this good style? Should I rather go for let
? When should I choose const
over let
?
推荐答案
const
可以在您不想要程序时正常使用
const
can be normally used when you don't want your program
-
将任何东西分配给变量
to assign anything to the variable
"use strict";
const a = 1;
a = 2;
将产生 TypeError:赋值给常量变量。
使用变量而不显式初始化
to use the variable without explicitly initializing.
"use strict";
const a;
将产生 SyntaxError:意外的令牌;
/ p>
will produce SyntaxError: Unexpected token ;
简单的说,我会说,
-
使用
const
每当你想要一些变量不被修改
use
const
whenever you want some variables not to be modified
使用 let
如果你想要的确是相反的 const
use let
if you want the exact opposite of const
使用 var
,如果您希望与ES5实现兼容,或者想要模块/功能级范围。
use var
, if you want to be compatible with ES5 implementations or if you want module/function level scope.
只有当您需要块级别的作用域时,才使用 let
,否则使用 let
或
var
不会有任何区别。
Use let
only when you need block level scoping, otherwise using let
or var
would not make any difference.
这篇关于const vs let调用require时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!