恰逢换工作之际,新公司的是以 ES6 + webpack + vue 为技术栈, 正好ES6是我下个学习目标, 因此买了阮老师的 ES6标准入门,也当是支持阮老师了.
笔记将会照着这本书的阅读展开而做一些笔记,为了对ES6理解更加深刻,做了个简单的gulp,让gulpES6进行编码,转为ES5,两边同时观察,让自己立即更加深刻!跟笔记有关的代码将全部放在github上.

let 和 const 命令

let

由于 JS 没有块级作用域,导致声明的变量在 {}内外都能访问,对此我们都是采用 function(){}来模拟块级作用域.

{
	var a = 1;
}
console.log(a); 	//=> 1

(function(){
	var b = 1;
})();
console.log(b);		//=> not defined

ES6中, let能很好的将变量局限在{}中.

{
	let a = 1;
	var b = 2;
}
console.log(a);		//=> not defined
console.log(b);		//=> 2

因此,在if,for等有块级作用域的语句里,将会发挥的很好!但是也带来了暂时性死区.只要作用域里有let语句,所声明的变量将会直接绑定在该作用域下.

var a = [];
for(var i = 0; i < 10; i++){
	a[i] = function(){
		console.log(i);
	}
}
a[5]();	//=> 10

var b = [];
for(let i = 0; i < 10; i++){
	b[i] = function(){
		console.log(i);
	}
}
b[5]();	//=> 5

var 具有变量提升,而 let不具有变量提升.因此使用let都需要声明后使用!
同时let不允许重复声明.

console.log(a);	//=> undefined
var a = 1;
console.log(a);	//=> 1
let a = 2;	//=> error

console.log(b);	//=> not defined

console.log(c);	//=> not defined
let c = 1;
console.log(c);	//=> 1;
let c = 2;	//=> error

PS: ES6let所带来的块级作用域,变量不提升以及暂时性死区,将减少很多'意外的情况',避免了ES5常有的错误.使得代码变得更加的严谨与安全!
PS1: 块级作用域对函数声明也是有效的.

const

const用来声明常量,一旦声明后,其值就不能改变.准确的说是该变量指向的地址将不能被改变.
const大部分效果与let一致,比如块级作用域,变量不提升,暂时性死区,不能重复声明等.

const a = 1;
console.log(a);	//=> 1;
a = 2;	//=> error

const b = [];
b = [1];	//=> error
b[0] = 1;
console.log(b);	//=> [1];

const c = {};
c = {name: 'ES6'} //=> error
c.name = 'ES6';
console.log(c);	//=> {name: 'ES6'}
posted on 2016-07-27 21:18  小玥光  阅读(134)  评论(0编辑  收藏  举报