ES6

第1节let

// ES6 — let

let a = 1;

if (1 === a) {
let b = 2;
}

for (let c = 0; c < 3; c++) {
// …
}

function letsDeclareAnotherOne() {
let d = 4;
}

console.log(a); // 1
console.log(b); // ReferenceError: b is not defined
console.log(c); // ReferenceError: c is not defined
console.log(d); // ReferenceError: d is not defined

// window
console.log(window.a); // 1
console.log(window.b); // undefined
console.log(window.c); // undefined
console.log(window.d); // undefined
As we can see, this time only variable a is declared as a global. let gives us a way to declare block scoped variables, which is undefined outside it.

//todo

let和const这两个的用途与var类似,都是用来声明变量的,但在实际运用中他俩都有各自的特殊用途。

demo1
var name = 'shitu91'

if(true) {
var name = 'shituketang'
console.log(name) //shituketang
}

console.log(name) //shituketang
使用var 两次输出都是shituketang,你现在看到的内层变量覆盖外层变量, 这是因为 ES5只有全局作用域(scope)和函数作用域,没有块级作用域。

而let则实际上为JavaScript新增了块级作用域。用它所声明的变量,只在let命令所在的代码块内有效。

let name = 'shitu91'
if (true) {
let name = 'shituketang'
console.log(name) //shituketang
}

console.log(name) //shitu91
demo2 计数的循环变量泄露为全局变量
var a = [];
for (var i = 0; i < 10; i++) {
a[i] = function () {
console.log(i);
};
}
a6; // 10
上面代码中,变量i是var声明的,在全局范围内都有效。所以每一次循环,新的i值都会覆盖旧值,导致最后输出的是最后一轮的i的值。
而使用let则不会出现这个问题。

var a = [];
for (let i = 0; i < 10; i++) {
a[i] = function () {
console.log(i);
};
}
a6; // 6
demo3
var clickBoxs = document.querySelectorAll('.clickBox')
for (var i = 0; i < clickBoxs.length; i++){
clickBoxs[i].onclick = function(){
console.log(i)
}

我们本来希望的是点击不同的clickBox,显示不同的i,但事实是无论我们点击哪个clickBox,输出的都是5。下面我们来看下,如何用闭包搞定它。
function iteratorFactory(i){
var onclick = function(e){
console.log(i)
}
return onclick;
}
var clickBoxs = document.querySelectorAll('.clickBox')
for (var i = 0; i < clickBoxs.length; i++){
clickBoxs[i].onclick = iteratorFactory(i)
}
const也用来声明变量,但是声明的是常量。一旦声明,常量的值就不能改变。
const PI = Math.PI

PI = 23 //Module build failed: SyntaxError: /es6/app.js: "PI" is read-only
当我们尝试去改变用const声明的常量时,浏览器就会报错。 const有一个很好的应用场景,就是当我们引用第三方库的时声明的变量,用const来声明可以避免未来不小心重命名而导致出现bug:+

const monent = require('moment')
// todo

let 关键词声明的变量不具备变量提升(hoisting)特性
let 和 const 声明只在最靠近的一个块中(花括号内)有效
当使用常量 const 声明时,请使用大写变量,如:CAPITAL_CASING
const 在声明时必须被赋值
Let:

New keywords added by ES6 that allow us to change the way we work with variables. JavaScript:

var name = 'Max';
console.log(name;

let new_name = 'Max';
console.log(new_name);
Console:

"Max"
"Max"
Here we see that both let and var do the same thing So what is the difference?

Using let allows us to control variable scoping. JavaScript:

if(true) {
let age = 24; // in the scope of the 'if' statment
}
console.log(age); // not in scope of the 'if' statement
Console:

"error"
"Reference Error: age is not defined
As another example, when using variables in a for loop, the index won't be used outside of the loop anymore!

posted @ 2017-07-11 10:01  前端兵哥哥  阅读(220)  评论(0编辑  收藏  举报