(译文)学习ES6非常棒的特性-深入研究var, let and const

时间:2023-01-06 21:50:36

Var

var firstVar; //firstVar被声明,它的默认值是undefined
var secondVar = 2; //secondVar被声明,被赋值2

先看一个例子:

var increment = 1;
if (increment === 1){
var increment; //重新声明
//Do something
}
console.log(increment); //这里会打印出什么?

声明提升

把所有的变量的声明都放到当前代码作用域的开头。

相当于这样:

var increment;
var increment;
increment = 1;
if (increment === 1){
...
}
console.log(increment); //print 1

在看一个例子:

var x = 0;
y = 1;
console.log(sumOf(x,y));
var y;
function sumOf(a, b){ return a + b; }

相当于这样:

var x;
var y;
function sumOf(a, b){ return a + b; }
x = 0;
y = 1;
console.log(sumOf(x,y));

声明提升只作用于声明,不作用于赋值,原来在哪一行赋值,还是原来的位置:

console.log(x);
x = 3;
var x = 1;
console.log(x);

将会打印:undefined, 1,而不是1, 3

执行上下文

代码执行的环境。

1 全局

2 函数

3 Eval函数内

注意代码块不是一个执行上下文。

function testMe(){
while(true){
var x = 2;
break;
}
console.log(x);
//仍然会打印出2
}

let

let是块作用域

function testMe(){
while(true){
let x = 2;
break;
}
console.log(x); //ReferenceError: x is not defined
}

1 这样的好处就是保证了变量不会被其他位置声明影响:

var x = 1;
{
let x = 3;
}
console.log(x); //仍然是1

2 可以不用闭包实现私有成员:

var Person;
{
let name;
Person = function(_name){
name = _name;
};
Person.prototype.getName = () => name;
}
var person = new Person('Maya');
console.log(name); //什么都不会打印
console.log(person.getName()); //Maya

3 声明提升不会作用域let

x = 5; //ok
y = 2; //ReferenceError: y is not defined
let y;
var x;

4 let声明的变量不会挂在window下面

var x = 5;
let y = 4;
console.log(this.x); //5
console.log(window.x); //5
console.log(this.y); //undefined
console.log(window.y); //undefined

5 重复声明会报错

(译文)学习ES6非常棒的特性-深入研究var, let and const

const

有些数据需要存起来作为常量,比如模板,字符串等等。如何保证它们不会被修改呢?

const!const和let一样是块作用域,它有let的所有特性:

①声明的变量只在块作用域内能用

②没有变量声明提升

③声明的变量不会给window

④不能被重复声明

另外一点:

⑤它必须初始化的时候就被赋值

const myConstants; //SyntaxError: Missing initializer in const declaration

⑥只能被赋值一次。

注意一点的是,如果const声明的是对象、数组的话,仍然可以修改:

const myConstant = {name: "Constant"};
myConstant = {name: "new Constant"}; //Error 不能被重新赋值
myConstant.name = "new Constant"; //OK 可以被修改
console.log(myConstant.name); //new Constant
const arr = [1, 2];
arr = [2,3]; //Error
arr[0] = 2; //OK
console.log(arr); //[2,2]

let和const的好处

1 避免污染全局window

2 避免隐藏错误:比如修改常量,错误的更新了变量的值等等

3 避免了不必要的变量提升

4 让代码更加可靠,更易组织,更易读。

原文:

https://medium.com/front-end-hacking/es6-cool-stuffs-var-let-and-const-in-depth-24512e593268

作者知乎/公众号:前端疯