JS的塊級範圍

來源:互聯網
上載者:User

標籤:聲明   blog   固定   foo   變數   建立   ...   typeerror   error   

今天帶來的是 “對《你不知道的js》中塊級範圍的總結” 分享:

1)用with從對象中建立出來的範圍只在with聲明中而非外部範圍有效,同時可以訪問已有對象的屬性並將其添加到已有對象上

代碼demo:

         var obj = {             a:1,             b:2,             c:3         };         with(obj){             a=3;             b=4;             c=5;
d=6; } console.log(obj);//3,4,5

2)try/catch 的catch分句會建立一個塊級範圍,其中聲明的變數僅在catch內部有效

代碼demo:

        try{            undefined();//執行一個非法操作來強制製造一個異常        }        catch(err){            console.log(err);//能夠正常執行        }        console.log(err);//ReferenceError:err is not defined

3)let用法:可以將變數綁定到所在的任意範圍中(通常是{...}內部)

代碼demo:

         for(i = 1; i < 5; i++){             console.log(i);//1 2 3 4         }         console.log(i);//5         for(let j = 1; j < 5; j++){             console.log(j);//1 2 3 4         }         console.log(j);//ReferenceError: j is not defined

由於let建立的是塊級範圍,所以外部無法訪問到let聲明的變數

4)const:可以用來建立塊範圍變數; 其值是固定的(常量),之後任何試圖修改值的操作都會引起錯誤

代碼demo:

        var foo = true;        if(foo){            var a = 2;            const b = 3;//包含在if中的塊範圍常量            a = 3;//正常            //b = 4;//錯誤            //console.log(b);//TypeError: invalid assignment to const `b‘(這裡說明其值為常量,之後不能更改其值)        }        console.log(a);//3
console.log(b);//ReferenceError!(這個異常可以證明const建立的塊範圍)

 

 

 

JS的塊級範圍

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.