ECMAScript (or ES) is a scripting-language specification standardized by Ecma International in ECMA-262 and ISO/IEC 16262. It was created to standardize JavaScript, so as to foster multiple independent implementations.
var camper = 'James'; var camper = 'David'; console.log(camper); // => 'David'
在实际使用过程中,你可能偶然的覆盖了之前的变量而你并不希望这样。
let解决了覆盖的问题
1 2
let camper = 'James'; let camper = 'David'; // throws an error
作用域的差别
1 2 3 4 5 6 7 8 9 10
var printNumTwo; for (var i = 0; i < 3; i++) { if(i === 2){ printNumTwo = function() { return i; }; } } console.log(printNumTwo()); // returns 3
上面的i是全局变量,所以返回的结果是3。
1 2 3 4 5 6 7 8 9 10 11 12 13
'use strict'; let printNumTwo; for (let i = 0; i < 3; i++) { if (i === 2) { printNumTwo = function() { return i; }; } } console.log(printNumTwo()); // returns 2 console.log(i); // returns "i is not defined"
上面的i是局部变量,仅在循环体内有效。因此结果为2。
2.2 const
被const限定的变量是只读的。
但是仍然可以改写const限定的数组
1 2 3 4 5
"use strict"; const s = [5, 6, 7]; s = [1, 2, 3]; // throws error, trying to assign a const s[2] = 45; // works just as it would with an array declared with var or let console.log(s); // returns [5, 6, 45]
使用Object.freeze保证对象不被更改
1 2 3 4 5 6 7 8 9
let obj = { name:"FreeCodeCamp", review:"Awesome" }; Object.freeze(obj); obj.review = "bad"; //will be ignored. Mutation not allowed obj.newProp = "Test"; // will be ignored. Mutation not allowed console.log(obj); // { name: "FreeCodeCamp", review:"Awesome"}