iT邦幫忙

第 11 屆 iT 邦幫忙鐵人賽

DAY 8
1
Modern Web

從Stack Overflow學前端系列 第 8

從StackOverflow上學CODING(8) 使用"let"與"var"的區別?

What's the difference between using “let” and “var”?

ECMAScript 6 introduced the let statement.
I've heard it that it's described as a "local" variable, but I'm still not quite sure how it behaves differently than the var keyword.
What are the differences? When should let be used over var?
ECMAScript 6中導入了 let 宣告,我聽說他就像是一個區域變數,但是我還不太清楚他跟var的本質上的不同,我應該使用哪個比較好?


The difference is scoping. var is scoped to the nearest function block and let is scoped to the nearest enclosing block, which can be smaller than a function block. Both are global if outside any block.
不同的地方在於範圍,var 的範圍只會影像到比較近的function,但是let則是在封閉的區域,甚至可以比function的區域還要在更小,兩個如果都不被限制在一個區域內而放在外面則都可以是全域變數
Also, variables declared with let are not accessible before they are declared in their enclosing block. As seen in the demo, this will throw a ReferenceError exception.
還有用let宣告的變數沒有辦法在跑到那行程式碼之前被使用

1.Global:
They are very similar when used like this outside a function block.
他們在function區域外的時候表現十分相似

let me = 'go';  // globally scoped
var i = 'able'; // globally scoped

However, global variables defined with let will not be added as properties on the global window object like those defined with var.
然而,let宣告的全域變數不會汙染到window的區域:

console.log(window.me); // undefined
console.log(window.i); // 'able'

2.Function:
They are identical when used like this in a function block.
他們在function內的表現是一樣的

function ingWithinEstablishedParameters() {
    let terOfRecommendation = 'awesome worker!'; //function block scoped
    var sityCheerleading = 'go!'; //function block scoped
}

3.Block
Here is the difference. let is only visible in the for() loop and var is visible to the whole function
不同點:let 只有在for()可以被看到,而var則是整個function內都可以獲取

function allyIlliterate() {
    //tuce is *not* visible out here

    for( let tuce = 0; tuce < 5; tuce++ ) {
        //tuce is only visible in here (and in the for() parentheses)
        //and there is a separate tuce variable for each iteration of the loop
    }

    //tuce is *not* visible out here
}

function byE40() {
    //nish *is* visible out here

    for( var nish = 0; nish < 5; nish++ ) {
        //nish is visible to the whole function
    }

    //nish *is* visible out here
}

4.Redeclaration:

Assuming strict mode, var will let you re-declare the same variable in the same scope.
var可以讓你在同一個範圍內重新宣告一樣內容的變數

'use strict';
var me = 'foo';
var me = 'bar'; // No problem, 'me' is replaced.

On the other hand, let will not:
而let則不會:

'use strict';
let me = 'foo';
let me = 'bar'; // SyntaxError: Identifier 'me' has already been declared

上一篇
從StackOverflow上學CODING(7)如何在 JS 檔案中導入另一個 JS 檔案
下一篇
從StackOverflow上學CODING(9)某物件是否存在的判斷式該怎麼寫
系列文
從Stack Overflow學前端30

尚未有邦友留言

立即登入留言