{
let aLet = 1;
var bVar = 2;
}
console.log(aLet); // Uncaught ReferenceError: aLet is not defined(…)
console.log(bVar); // 2
for (let i = 0; i < 3; i++) {}
console.log(i); // Uncaught ReferenceError: i is not defined(…)
// 使用var变量
var a = [];
for (var i = 0; i < 10; i++) {
a[i] = function () {
console.log(i);
};
}
a[6](); // ?结果
// 使用let变量
var a = [];
for (let ii = 0; ii < 10; ii++) {
a[ii] = function () {
console.log(ii);
};
}
a[6](); // ?结果
(function(){
var str1 = "1";
var fun1 = function(){};
var str2 = "2";
var str3 = "3";
})();
// 同上代码
(function(){
var str1,fun1,str2,str3;
str1 = "1";
fun1 = function(){};
str2 = "2";
str3 = "3";
})();
console.log(foo); // undefined
console.log(bar); // Uncaught ReferenceError: bar is not defined(…)
var foo = 2;
let bar = 2;
// 使用var
var tmp = 123;
if (true) {
console.log(tmp);
var tmp;
}
// 使用let,运行结果
var tmp = 123;
if (true) {
console.log(tmp);
let tmp;
}
// 未使用let语句
typeof myData;
// 使用let语句
{
typeof myData;
let myData = 'myData';
}
// Uncaught SyntaxError: Unexpected token
function fun1() {
let num1 = 10;
var num1 = 1;
}
// Uncaught SyntaxError: Unexpected token
function fun2() {
let num2 = 10;
let num2 = 1;
}
function func(arg) {
let arg; // 报错
}
function func(arg) {
{
let arg; // 不报错
}
}
// 场景一
var date = new Date();
function fun() {
console.log(date);
if (false) {
var date = "hello world";
}
}
fun();
// 场景二
var str = 'hello';
for (var j = 0; j < str.length; j++) {
console.log(str[j]);
}
console.log(j);
{{{{
{let insane = 'Hello World'}
console.log(insane); // Uncaught ReferenceError: insane is not defined
}}}};
{{{{
let insane = 'Hello World';
{let insane = 'Hello World'}
}}}};
// IIFE写法
(function () {
var tmp = ...;
...
}());
// 块级作用域写法
{
let tmp = ...;
...
}
// 情况一
if (true) {
function fun() {}
}
// 情况二
try {
function fun() {}
} catch(e) {
}
// ES6严格模式
'use strict';
if (true) {
function f() {}
}
注意点
const COLOR; //Uncaught SyntaxError: Missing initializer in const declaration
const与let相同特性
if (true) {
const MAX = 5;
}
console.log(MAX); // Uncaught ReferenceError: MAX is not defined
复合类型(Object,Array等)的变量,可对其值进行修改,即const的定义保证了变量名指向地址不变。
// Array
const foo = {};
foo.prop = 123;
console.log(foo);
foo = {}; //Uncaught TypeError: Assignment to constant variable.
// Object
const arr = [];
arr.push('Hello');
arr.length = 0;
arr = ['World']; // Uncaught TypeError: Assignment to constant variable
使用const定义复合型变量达到真正的对象不可变,可以使用Object.freeze()方法冻结对象。
// 冻结对象和属性
var constantize = (obj) => {
Object.freeze(obj);
Object.keys(obj).forEach( (key, value) => {
if ( typeof obj[key] === 'object' ) {
constantize( obj[key] );
}
});
};
const person = {name: 'penglu', age: 27};
constantize(person);
person.name = 'lee'; //无法修改,但是不会报错
const arr = ['one', 'two'];
constantize(arr);
arr.push('three'); // Uncaught TypeError: Can't add property three, object is not extensible
let命令、const命令、class命令声明的全局变量,不属于全局对象的属性
实例
const PI = 3.1415926;
PI = 123; // Uncaught TypeError: Assignment to constant variable