先看let和var:瀏覽器
1. 函數
console.log(a); // undefined var a = 3;
console.log(a); // Uncaught ReferenceError: Cannot access 'a' before initialization let a = 3;
let fn = function () {};
2.spa
var x = 3; console.log(window.x); // 3 let y = 3; console.log(window.y); // undefined
function fn() { var x = 1; y = 2; console.log(fn.x); // undefined console.log(fn.y); // undefined } fn(); console.log(window.x); // undefined console.log(window.y); // 2
3.指針
var y = 21; var y = 24; console.log(y); // 24
console.log('OK'); // Uncaught SyntaxError: Identifier 'x' has already been declared let x = 21; console.log(x); let x = 24; console.log(x);
4.code
if (1 === 1) { let x = 3; console.log(x); } console.log(x); // Uncaught ReferenceError: x is not defined
let a = 1; switch (a) { case 1: let x = 2; break; } console.log(x); // Uncaught ReferenceError: x is not defined
try { let x = 100; console.log(x); // 100 console.log(a); } catch (e) { let y = 200; console.log(y); // 200 } console.log(x);// Uncaught ReferenceError: x is not defined
try { let x = 100; console.log(x); // 100 console.log(a); } catch (e) { let y = 200; console.log(y); // 200 } console.log(y); // Uncaught ReferenceError: y is not defined
從上能夠看出,let存在塊級做用域,var則沒有。對象
再看let(var)和constblog
let x = 10; x = 20; console.log(x); // 20
const y = 10; y = 20; // Uncaught TypeError: Assignment to constant variable. console.log(y);
const obj = {a: 10}; obj.b = 20; console.log(obj); // {a: 10, b: 20}