我可以完全停止使用var吗?
我正在学习Java课程,所有声明都使用块作用域( int,double,boolean等
).在JavaScript中, var
是函数范围.
I'm taking a Java course and all declarations use block scope( int, double, boolean, etc.
). In JavaScript however var
is function scope.
let
出现在ES6中,为JS开发人员提供了块作用域.我正在调整自己的编码风格,并选择一起摆脱 var
.
let
came along in ES6 and gave JS developers block scope. I'm adjusting my coding style and am opting to get rid of var
all together.
好吗?
好吗?
主要是;可能完全是.在 非常 的少数情况下,您想使用 var
而不是 let
/ const 代码>出于技术(而非风格)原因:
Mostly; possibly entirely. There are very few situations where you would want to use var
instead of let
/const
for technical (rather than style) reasons:
-
如果要声明一个成为全局对象属性的全局变量(全局
let
,const
和class
创建全局变量,但它们不会成为全局对象的属性.
If you want to declare a global variable that becomes a property of the global object (global
let
,const
, andclass
create globals, but they don't become properties of the global object).
当然,您可以使用 this.varName = ...
而不是 var varName
,因为在全局范围内的 this
是全局的对象.
Of course, you could use this.varName = ...
instead of var varName
, since this
at global scope¹ is the global object.
如果您要拥有多个文件,其中任何一个文件可能是定义相同全局变量的第一个"(但不是最后一个),这在较旧的模块格式中很常见,例如:
If you want to have several files where any of them may be the "first" (but not last) to define the same global, as is common in older module formats, e.g.:
var MyApp = MyApp || {};
MyApp.something = /*...*/;
之所以可行,是因为如果已经声明了 MyApp
,则会默默地忽略 var MyApp
部分;与 let
等效的结构将失败,因为如果在当前作用域中已经声明了标识符,则无法使用它.
That works because the var MyApp
part is silently ignored if MyApp
is already declared; the equivalent structure with let
would fail because it cannot be used if the identifier is already declared in the current scope.
当然,您现在可能正在使用新的模块格式.:-)如果不是,那么您也可以这样做
Of course, you're probably using a new module format by now. :-) And if you aren't, again you could do
this.MyApp = this.MyApp || {};
MyApp.something = /*...*/;
在全球范围内.¹
[在将其用作循环计数器的函数中,使用 var
而不是 let
会对性能产生较小的影响..现代版本的浏览器的最新版本几乎消除了这一细微的好处(无论如何它都是微不足道的.)
[There used to be a minor performance benefit to using var
instead of let
in a function where it was used as a loop counter. Recent versions of modern browsers all-but-remove that minor benefit (and it was minor anyway).]
¹注意,模块(ES2015模块,Node.js模块,大多数捆绑器...)中的顶级代码在全局范围内不是.它在模块范围内.另外请注意,在ES2015模块的顶层, this
的值为 undefined
.
¹ Note that top-level code in a module (ES2015 module, Node.js module, most bundlers...) is not at global scope. It's at module scope. Also note that at the top level of an ES2015 module, this
has the value undefined
.