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

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.

主站蜘蛛池模板: 商城县| 阳山县| 沂水县| 漠河县| 定陶县| 乌海市| 黔东| 白银市| 仁布县| 平乐县| 巨野县| 南皮县| 清镇市| 红安县| 松溪县| 印江| 定陶县| 鹿泉市| 麟游县| 蛟河市| 万州区| 南皮县| 安庆市| 绥江县| 阿城市| 六盘水市| 林西县| 盱眙县| 兴宁市| 岚皋县| 社旗县| 犍为县| 镇远县| 容城县| 临猗县| 宜阳县| 西畴县| 南投县| 黄骅市| 郑州市| 濉溪县|