js範圍和作用鏈

來源:互聯網
上載者:User

標籤:style   blog   io   ar   color   sp   java   on   div   

js中函數嵌套是非常普遍的,那麼子啊函數嵌套中,變數時怎麼尋找的?

答:首先在內層中尋找,找不到的話就跑的外層尋找,

……直到跑到window頂層(全域)為止

 

——————————————————————————————

聲明變數時加var和不加var的區別,

答:加var才是聲明變數。不加的話是賦值操作(不要狹隘的理解為聲明了一個全域變數),會在函數內部找變數,找不到往上層找,還沒有的話找到window,並賦值。

  js中 允許在定義變數的時候 不加var 修飾符。
-》不加var 修飾符。js會在當前範圍下尋找上下文是否定義了此變數, 如果沒有找到則會為這個變數分配記憶體。當且將其視為window的成員。 也就是全域變數。
-》如果加了var 修飾符。 js會重新為這個變數分配記憶體,不論當前上下文中是否已經定義過了。這個變數的範圍就為當前上下文。 即局部變數。

 1 <script type="text/javascript"> 2  3 function t1() { 4     var d; 5  6     function t2() { 7         d = 5; 8         e = 6; 9     }10 11     t2();12 }13 14 15 t1();16 17 console.log(e); // 618 console.log(d); // d is not defined錯誤19 console.log(window.d); // undefined20 21 /*22 注意:23 以window.xxx引用全域變數,尋找不到,做為某個屬性不存在,返回undefined24 直接以xxx引用某命題,尋找不到,則是報xxx is not defined錯誤25 */

 

 1 <script type="text/javascript"> 2  3 /* 4 範圍考試 5  6 注:這是一個極容易出錯,又極基礎的JS面試題 7 */ 8  9 10 /*11 var str1 = ‘global‘;12 13 function  t1() {14     console.log(str1);15     console.log(str2);16 17     str2 = ‘local‘;18 }19 20 t1();  21 22 23 24 常見的3種答案25 global , local26 global , undefined27 global , str2 is not defined錯誤28 29 分析: 30 31 19行執行, 在t1內尋找str1--沒有,又在window上尋找str1,有. 列印global32 20行執行, 在t1內尋找str2--沒有,又在window上尋找str2,沒有. 報str2 is not defined錯誤33 22行: (實際上出錯,沒執行到這一些)  才把全域的str2變數賦上值34 */35 36 37 var str1 = ‘global‘;38 39 function  t1() {40     console.log(str1);41     console.log(str2);42 43     var str2 = ‘local‘;44 }45 46 t1();   // global undefined47 48 /*49 解釋:50 51 js代碼自上而下執行!52 53 但是----------54 js代碼在整體運行分:55 56 詞法分析期57 運行期58 59 自上而下執行之前 , 先有一個"詞法分析過程"!60 61 62 此上面的結果為例:63 64 65 1步:分析t1函數66 67 t1{68 var str2    // 分析出 t1內有str2局部變數. 注意此時函數未執行,因此str2的值是undefined69 }70 71 2步: 執行t1函數72     console.log(str1);   // global73     console.log(str2);   // undefined74     str2 = ‘local‘;  // 此時,str2的值為local75 76 */77 78 79 /*80 81 詞法分析是我們的一個重點82 83 */84 85 86 87 88 </script>

 

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.