官术网_书友最值得收藏!

Scoping

In the old days, we used to always go with the var statement for variable declarations. ES2015 introduces two new declaration variables--let and const. The var statement declares a variable in a function scope:

(function(){ 
var foo = 1;
if ( true ) {
var foo = 2;
console.log( foo );
}
console.log( foo );
}());
$ node es6.js
2
2

A variable declared with var (foo) spans the entire function scope, meaning that every time we reference it by name, we target the same variable. Both let and const operate on block scopes (if statement, for/while loops, and so on) as shown:

 (function(){ 
let foo = 1;
if ( true ) {
let foo = 2;
console.log( foo );
}
console.log( foo );
}());
$ node es6.js
2
1

As you can see from the preceding example, we can declare a new variable in a block and it will exist only within that block. The statement const works the same, except it defines a constant that cannot be reassigned after it was declared.

主站蜘蛛池模板: 旬邑县| 遵化市| 沧州市| 靖远县| 建昌县| 高要市| 杂多县| 东宁县| 溧阳市| 固镇县| 卫辉市| 马山县| 甘肃省| 安康市| 兰州市| 遂宁市| 仁化县| 牡丹江市| 高雄县| 马公市| 宜宾县| 罗定市| 湖口县| 铁岭市| 亚东县| 合川市| 杭州市| 维西| 新龙县| 江都市| 巴楚县| 仙游县| 特克斯县| 故城县| 凭祥市| 沽源县| 舟山市| 长沙县| 喀什市| 吉水县| 万州区|