前言
除了var创建新元素的命令的–>let,const
关键字
var,let,const
一、定义
var
默认全局变量
缺省的定义是全局变量
var hw = 'hello word';
console.log("hw=" + hw);
hwAll = "hello All";
console.log("hw=" + hw);
for (var index = 0; index < 1; index++) {
var inCon = "inCon";
console.log("index" + index+",hw=" + hw + ",inCon="+inCon);
}
console.log(",inCon="+inCon);
let
局部变量,仅在方法内有效
for (let index = 0; index < 1; index++) {
let inConLet = "inConLet";
console.log("index" + index+",hw=" + hw + ",inConLet="+inConLet);
}
//如果不在作用域会报
//异常代码
D:\vuecode\es6\hw.js:20
console.log(",inConLet="+inConLet);
^
ReferenceError: inConLet is not defined
at Object.<anonymous> (D:\vuecode\es6\hw.js:20:26)
at Module._compile (internal/modules/cjs/loader.js:1158:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1178:10)
at Module.load (internal/modules/cjs/loader.js:1002:32)
at Function.Module._load (internal/modules/cjs/loader.js:901:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)
at internal/main/run_main_module.js:18:47
const
声明常量不能进行修改
const num = "111";
num = "111111";
//如果不在作用域会报
//异常代码
num = "111111";
^
TypeError: Assignment to constant variable.
at Object.<anonymous> (D:\vuecode\es6\hw.js:25:5)
at Module._compile (internal/modules/cjs/loader.js:1158:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1178:10)
at Module.load (internal/modules/cjs/loader.js:1002:32)
at Function.Module._load (internal/modules/cjs/loader.js:901:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)
at internal/main/run_main_module.js:18:47
二、对比
功能\命令 | var | let | const |
---|---|---|---|
作用域 | 全局 | 作用域内 | 作用域内 |
是否可修改 | 是 | 是 | 否 |
变量值 | 是 | 是 | 否 |
总结
1 根据实际场景使用命令
2 最小粒度使用命令