2017-05-19 162 views
0

我知道關於局部變量和全局變量的基本知識,但任何人都可以解釋這兩個代碼示例之間的區別嗎?循環中的局部變量和全局變量

var elements = document.querySelectorAll('.classname'); 
for (var i = 0; i < elements.length; i++) { 
    // do something 
} 

var elements = document.querySelectorAll('.classname'); 
for (i = 0; i < elements.length; i++) {     // <-- removed "var" before "i = 0" 
    // do something 
} 
+0

以及技術上'i'是第一個代碼全局,如果它是不是一個塊中運行。 – epascarello

回答

1

隨着var關鍵字,沒有 「塊」 的範圍,所以聲明是任一 「功能」 或作用域 「全局」。在循環中聲明變量或在if語句的真/假分支中聲明變量的事實不會創建僅限於該代碼塊的變量。這與大多數編譯語言完全不同。

ECMAScript 2016(又名ES6)將關鍵字let引入「塊」範圍。

因此,如果您省略了關鍵字var並且只是在函數中創建一個新變量,那麼該變量將變爲全局變量,因爲JS運行時不知道您想要的範圍。

下面是一些例子:

// Outside of functions, the var keyword creates global variables 
 
var g = "global"; 
 

 
function foo(){ 
 
    // Inside of functions, the var keyword creates "local" or function scoped variables 
 
    var l = "local"; 
 
    
 
    // But, omitting the "var" keyword, whereever you do it, creates a global 
 
    oops = "global"; 
 
    
 
    // But, creating a function scoped variable of the same name as a variable in a higher 
 
    // scope, just hides the one from the higer scope as long as the code runs in the smaller 
 
    // scope: 
 
    var g = "local"; 
 

 
    // Other than global and function, the var keyword does not create "block" scope: 
 
    if(true){ 
 
    var x = "surprise!"; 
 
    } 
 
    
 
    // Now, we'll see what we get when we are in the local scope: 
 
    console.log(g);  // "local", not "global" because smaller scope prevails 
 
    console.log(l);  // "local"; 
 
    console.log(oops); // "global" 
 
    console.log(x);  // "surprise!" because x has function scope, not block 
 

 
} 
 

 
foo(); 
 

 
    // Now, we'll see what is available back in the global scope: 
 
    console.log(g);   // "global" because now we are in the global scope 
 
    console.log(typeof l); // It's an error to try to access directly, type is undefined 
 
    console.log(oops);  // "global" because we omitted var and it became global 
 
    console.log(typeof x); // It's an error to try to access directly, type is undefined

+0

OT,你是否曾經爲MSMQ嚮導工作過,名叫Klaus? –