iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 14
0
tags: 2019年鐵人賽JS

var

摘自MDN
使用var區塊中定義的變數,其存取範圍是整個函式或是腳本,即為Execution Context的範圍中。

意思就是用 var 宣告時,其存取範圍是整個全域或整個function。

範例

var a = 2; 
{
    var a = 4;
    console.log(a); //4
}
console.log(a); //4

var 宣告在整個全域範圍,存取範圍是整個全域。
第一個 a 和第二個 a 是ㄧ樣的記憶體位置。

let和const

摘自MDN
用 let 或 const 宣告時,其存取範圍只有本身定義的區塊中。

範例

let a = 2; 
{
    let a = 4;
    console.log(a); //4
}
console.log(a); //2

第一個 a 宣告於整個全域範圍,存取範圍是整個全域。
第二個 a 宣告於 block 裡,存取範圍是整個 block。
兩者是不ㄧ樣的記憶體位置。

var和let的全域scope

範例

var dad = "爹";
console.log(window.dad); //會出現"爹"
let mom = "娘";
console.log(window.mom);//會出現 undefined

var 在全域下的變數會在 window 物件上
let 在全域下的變數不會在 window 物件上,表示雖然是在全域環境所宣告的變數,但不會污染全域。

function

範例

var b = "全域";
function test(){
    var b = "var";
    {
      let b = "let"
      console.log(b); //let
    }
    console.log(b); //var
}
test();
console.log(b); //全域

第一個 b 宣告於整個全域範圍,存取範圍是整個全域。
第二個 b 宣告於 function 裡,存取範圍是整個function。
第三個 b 宣告於 block 裡,存取範圍是整個 block。
三個 b 都是不ㄧ樣的記憶體位置。

小結

var的存取範圍

  1. 宣告在function外是全域scope(會在 window 物件上)
  2. 宣告在function內是function scope
  3. 沒有block scope

let的存取範圍

  1. 宣告在function外是全域scope(不會在 window 物件上)
  2. 宣告在{}內是block scope
  3. let不能重複宣告

const的存取範圍

  1. 宣告在function外是全域scope(不會在 window 物件上)
  2. 宣告在{}內是block scope
  3. const不能重複指定值,也不能重複宣告。

上一篇
|D13| CSS - Block fomatting context(BFC)
下一篇
|D15| JS - `<form>` 表單
系列文
前端菜焦阿日記30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
Chris
iT邦新手 4 級 ‧ 2018-10-30 08:08:44

let 可以重複宣告嗎??

mangoSu iT邦新手 5 級 ‧ 2018-11-01 23:44:22 檢舉

謝謝勘誤~let不能重複宣告

我要留言

立即登入留言