2017-05-19 27 views
0

私はローカル変数とグローバル変数に関する基礎を知っていますが、誰もこの2つのコード例の違いを説明できますか? varキーワードでループ内のローカル変数とグローバル変数

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

宣言は、 "機能" は、スコープまたは "グローバル" されているいずれかのように、何の "ブロック" の範囲は、存在しません。 ifステートメントのループまたは真/偽のブランチで変数を宣言しても、そのコードブロックのみにスコープを持つ変数は作成されません。これは、ほとんどのコンパイルされた言語とはまったく異なります。

ECMAScript 2016(a.k.a.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、以前はKlausという名前のMSMQウィザードで作業していましたか? –

関連する問題