- Cross-platform Desktop Application Development:Electron,Node,NW.js,and React
- Dmitry Sheiko
- 176字
- 2021-07-15 17:36:26
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.
推薦閱讀
- 新編Visual Basic程序設計上機實驗教程
- PHP動態網站程序設計
- iOS Game Programming Cookbook
- Flutter開發實戰詳解
- Visual Basic 6.0程序設計計算機組裝與維修
- Mastering Business Intelligence with MicroStrategy
- C語言程序設計簡明教程:Qt實戰
- C編程技巧:117個問題解決方案示例
- Vue.js光速入門及企業項目開發實戰
- 跟戴銘學iOS編程:理順核心知識點
- Java EE 7 with GlassFish 4 Application Server
- MySQL 8從零開始學(視頻教學版)
- Python預測分析實戰
- 現代CPU性能分析與優化
- SEO教程:搜索引擎優化入門與進階(第3版)