In function: (function是砖墙,function中的var不可以穿透砖墙,是局部变量)
function myFunction {
var a = 1;
let q = 2;
console.log(a); //1
}
console.log(a); //undefined
console.log(q); //undefined
function b {
console.log(a); //undefind
}
var此时作为全局变量,可以被myFunciton access到,且值被修改
var a = 1;
function myFunction {
a = a + 100;
console.log(a); //101 , a现在是global scope的变量
}
myFunction(); //执行myFunction中的内容
console.log(a); //101
对于let 在function中,let 在外面定义,是global scope variable,可以被function读取,改变值
let a = 1;
function myFun(){
a = a + 100;
console.log(a); // 101
}
myFun();
console.log(a); //101
对于const 在function中,
const a = 1;
function myFun(){
a = a + 100; // 报错,因为 a是常量const,不可以改变a的值
console.log(a);
}
myFun();
console.log(a);
In if/else, while: (if/else, while不是砖墙,var穿透为global变量)
if {
var a = 1;
console.log(a); //1
let b = 2;
const c = 3;
}
console.log(a); //1
console.log(b);//undefined
console.log(c);//undefined
if对于全局的let和var是可以穿透的,可以在if中access到,并且改变值
var b = 100;
let c = 1000;
const d = 11;
if(b === 100){
b = b + 1;
console.log(b); // 101
c = c + 1;
console.log(c); //1001
}
console.log(b); //101
console.log(c); //1001
综上,在写javascript时,尽量用let,不要用var,var是global变量,let是局部变量
可以参考mdn文档中的信息:
- var
var x = 1;
if (x === 1) {
var x = 2;
console.log(x);
// expected output: 2
}
console.log(x);
// expected output: 2
- let
let x = 1;
if (x === 1) {
let x = 2;
console.log(x);
// expected output: 2
}
console.log(x);
// expected output: 1
- const
const number = 42;
try {
number = 99;
} catch(err) {
console.log(err);
// expected output: TypeError: invalid assignment to const `number'
// Note - error messages will vary depending on browser
}
console.log(number);
// expected output: 42
const在js中不保护inside的东西
const的array可以被push新元素,不可以重新初始化