(function() {
var testValue = 'hello';
var testFunc = function () {
console.log('just test'); };
})();
console.log(window.testValue);// undefined
console.log(window.testFunc);// undefined
趣题:
var x = 10,
y = 20;
[y, x] = [x, y]
console.log(x, y)
let 与 const 声明
ES6 的 let 和 const 都是新引入的关键字。它们不会被提升,而且是块作用域。也就是说被大括号包围起来的区域声明的变量外部将不可访问。
let 声明
过早访问 let 声明的引用导致的这个 referenceerror 叫做临时死亡区错误.你在访问一个已经声明但还没有初始化的变量. 创建一个块作用域.
let g1 = 'global 1'
let g2 = 'global 2'
{ /* Creating a new block scope */
g1 = 'new global 1'
let g2 = 'local global 2'
console.log(g1) // 'new global 1'
console.log(g2) // 'local global 2'
console.log(g3) // ReferenceError: g3 is not defined
let g3 = 'I am not hoisted';
}
console.log(g1) // 'new global 1'
console.log(g2) // 'global 2'
const tryMe = 'initial assignment';
tryMe = 'this has been reassigned'; // TypeError: Assignment to constant variable.
// You cannot reassign but you can change it…
const array = ['Ted', 'is', 'awesome!'];
array[0] = 'Barney';
array[3] = 'Suit up!';
console.log(array); // [“Barney”, “is”, “awesome!”, “Suit up!”]
const airplane = {};
airplane.wings = 2;
airplane.passengers = 200;
console.log(airplane); // {passengers: 200, wings: 2}
常见例子
function outer() {
let a = 1;
function inner() {
let b = 2;
function innermost() {
let c = 3;
console.log(a, b, c); // 1 2 3
}
innermost();
console.log(a, b); // 1 2 — 'c' is not defined
}
inner();
console.log(a); // 1 — 'b' and 'c' are not defined
}
{ /* Original code */
console.log(i); // undefined
var i = 10
console.log(i); // 10
}
{ /* Compilation phase */
var i;
console.log(i); // undefined
i = 10
console.log(i); // 10
}
// ES6 let & const
{
console.log(i); // ReferenceError: i is not defined
const i = 10
console.log(i); // 10
}
{
console.log(i); // ReferenceError: i is not defined
let i = 10
console.log(i); // 10
}
function greeting() {
console.log(s) // undefined
if(true) {
var s = 'Hi';
undeclaredVar = 'I am automatically created in global scope';
}
console.log(s) // 'Hi'
}
console.log(s); // Error — ReferenceError: s is not defined
greeting();
console.log(undeclaredVar) // 'I am automatically created in global scope'
let a = 2;
if(a> 1){
let b = a +1;
console.log(b) //6
for(let i = a; i <=b;i ++){
let j = i +10;
console.log(j)
}
//12 13 14 15 16
let c = a+ b;
console.log('c: ', c);
}
总结
默认使用 const, 只在确实需要改变的时候使用 let, 这样就可以在某种程度上实现代码的不可变。从而防止某些错误的产生。