标签:时报 type 创建 for initial var bee style red
先看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.
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.
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)和const
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}
标签:时报 type 创建 for initial var bee style red
原文地址:https://www.cnblogs.com/ronaldo9ph/p/12264858.html