js 变量定义方式
Var(万能)
变量可以没有初始值 会报undefined但不会报错
变量可以修改
变量可以覆盖 (重复定义)
函数内重复定义对函数外无影响
函数内重新赋值对函数外有影响
var a = 1; var b; var c = 2; console.log(a);//1 console.log(b);//undefined console.log(c);//2 var c = 3 ; console.log(c);//3 c = 4; console.log(c);//4 k(); function k(){ var c = 5; console.log(c);//5 c = 6; console.log(c);//6 } console.log(c);//4 m(); function m(){ c = 7; } console.log(c);//7
Let(局部使用)
块级作用域
函数内外不影响 避免了全局变量的污染
没有得到广泛的支持 (Sublime Text 3 Nodejs 下 Run)
let a = 1; let b; let c = 2; console.log(a);//1 console.log(b);//undefined console.log(c);//2 let c = 3 ;//SyntaxError: Identifier 'c' has already been declared c = 4; console.log(c);//4 k(); function k(){ var c = 5; console.log(c);//5 c = 6; console.log(c);//6 } console.log(c);//4
Const(只能看不能动)
变量必须有初始值
变量值不可更改
变量值不可覆盖
const a = 1; const b;//SyntaxError: missing = in const declaration const c = 2; console.log(a);//1 console.log(c);//2 const c = 3 ;//SyntaxError: redeclaration of const c c = 4;//TypeError: invalid assignment to const `c' k(); function k(){ const c = 5; console.log(c);//5 } console.log(c);//2