2015-07-01 26 views
3

因此,努力學習一些關於ES6,我就過來了這個鏈接,http://es6-features.org/#BlockScopedVariables這個循環如何在Es5/Es6上工作?

// ES6 

let callbacks = [] 
for (let i = 0; i <= 2; i++) { 
    callbacks[i] = function() { return i * 2 } 
} 
callbacks[0]() === 0 
callbacks[1]() === 2 
callbacks[2]() === 4 

// ES5 

var callbacks = []; 
for (var i = 0; i <= 2; i++) { 
    (function (i) { 
     callbacks[i] = function() { return i * 2; }; 
    })(i); 
} 
callbacks[0]() === 0; 
callbacks[1]() === 2; 
callbacks[2]() === 4; 

我想知道爲什麼在ES5方法中,我們使用的是直接的函數返回I * 2的值?

但是在ES6中,只分配循環中的值有效?

基本上,

  1. 想知道爲什麼這種差異會出現?
  2. 該循環如何執行?
  3. 我發現區別是由於「塊範圍(讓)&全局範圍(var)」,但想知道更多關於執行/運行點?
  4. 所以我們不想使用即時函數來保存ES6中變量的當前狀態?
+0

的[JavaScript中的潛在的重複 - 「讓」 的關鍵字與「變種「關鍵字」(http://stackoverflow.com/questions/762011/javascript-let-keyword-vs-var-keyword) –

+0

@ TaoP.R。如果重複,請解釋該循環如何工作? – Sathish

+0

另請參閱[let'和block作用域循環的說明](http://stackoverflow.com/a/30900289/1048572)(不確定是否重複) – Bergi

回答

4

正如你所說的,所不同的是使用let它創建了一個塊範圍的變量VS使用var它創建一個執行上下文範圍的變量之間 - 不僅僅是全球性的,但在執行功能的範圍。

// ES6 
var callbacks = []; 
for (let i = 0; i <= 2; i++) { 
    // A new LexicalEnvironment is established here, where i only survives 
    // the duration of this 'for' statement 
    // So we can safely say that when function() is called, `i` will have 
    // the value we assign to it here 
    callbacks[i] = function() { return i * 2 } 
} 

然而,在ES5 ...

// LexicalEnvironment is established here and `i` is declared 
var callbacks = []; 
for (var i = 0; i <= 2; i++) { 
    callbacks[i] = function() { return i * 2; }; 
} 
// `i` is still available now and its value is currently 2 
// So when you execute `callbacks[2]()` the LexicalEnvironment where `i` was set 
// is the one where i === 3 
callbacks[0]() // 6 
callbacks[1]() // 6 
callbacks[2]() // 6 

現在,使用ES5的IIFE ...

var callbacks = []; 
for (var i = 0; i <= 2; i++) { 
    // Much like using let, by declaring an IIFE here, we are telling the engine 
    // to create a new LexicalEnvironment to store the current value of i 
    (function (i) { 
     callbacks[i] = function() { return i * 2; }; 
    })(i); 
} 
+0

Ecmascript6支持提升嗎? – Sathish

+0

@Sathish是的。就提升而言,除了你不能訪問聲明的'let'變量超出它的塊範圍 – CodingIntrigue

+0

感謝您提供清晰的信息,相同的規則是'let'作爲'var'。 – Sathish