DAY 8
0
Modern Web

## 1. 函數作用域

``````let a = 123 // 全域作用域

function func() {
var b =  456
console.log(a)
}

console.log(a) // apple

console.log(b) // Uncaught ReferenceError: b is not defined

func() //123
``````

``````// 全域作用域

function func() { //作用域A
let a = "coffee"

function func1() { //作用域B
let a = "apple"
let b = "banana"
// 這裡可放許多要對外隱藏的變數

console.log(a);
}

console.log(a) // coffee
console.log(b) // Uncaught ReferenceError: b is not defined
func1() //apple
}

func();
``````

## 2. ES6帶來的Object Scope

`````` function test() {
{
function inner() {
}
}
inner()
}

test() // inner function
``````

``````function run() {
var foo = "Foo";
let bar = "Bar";

console.log(foo, bar); // Foo Bar

{
var moo = "Mooo"
let baz = "Bazz";
console.log(moo, baz); // Mooo Bazz
}

console.log(moo); // Mooo
console.log(baz); // ReferenceError
}

run();
``````

## 3. 為什麼要新增Object scope?

### 3.1 var聲明存在副作用 --- Hoisting

``````console.log(a); // undefined
console.log(b); // ReferenceError
var a = "car"; // 聲明提前
let b = "123"; //由let聲明的不存在提前特性
``````

### 3.2 var聲明變數有汙染疑慮

``````for(var i = 0; i < 100; i++) {
// many code
}

// many code
console.log(i) // 100
``````

``````for(let i = 0; i < 100; i++) {
// many code
}

// many code
console.log(i) // ReferenceError
``````

JavaScript學習日記30