Files
hexo-blog/source/_posts/es6-下定义变量,let大法好!.md
2020-11-24 17:45:32 +08:00

45 lines
1.6 KiB
Markdown
Raw Permalink Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
---
title: ES6 下定义变量,let大法好!
id: '52'
categories:
- 分享
tags:
- ES6
- let
- 作用域
date: 2016-06-16 22:37:51
---
  var _声明的变量作用域不是块级的,会扩大变量的作用域,可能造成变量污染。_ let _声明的变量作用域就更精确,离开作用域变量就销毁。_ const _顾名思义就是常量了。_ **变量作用域更加精准** 不用担心变量作用域自动提升,造成上一级或全局变量值被覆盖。 举个栗子:
``` js
let a = 1;
var b = 1;
if (true) {
let a = 2;
var b = 2;
}
console.log(a) // 输出 1
console.log(b) // 输出 2
```
**变量作用域可控性更好** let 的作用域是根据代码块(enclosing block)来判定的,而 var 的作用域是根据函数块(function block)来判定的。这样的话,如果我们的变量都使用 let/const 来声明,那么以前的立即执行函数就不需要了,我们只要加一个代码块就好了。 举个栗子:
``` js
{
let a = 1;
}
console.log(a) // 输出 a is not defined
```
**Runtime自动检查重复声明的函数并报错** 在同一个作用域内不允许重复声明变量。 举个栗子:
``` js
if (true) {
let a = 1;
let a = 2;
}
```
Runtime会报错:Uncaught SyntaxError: Identifier 'a' has already been declared 有了更加清晰的作用域,我们的代码就能够更好被预测,也更好维护。 有了更容易控制的作用域可以让我们减少很多立即执行的函数。 Runtime的自动检查可以避免不必要,甚至是错误的代码声明。