阅读目录
共同点
- 共同点
- var
- let
- const
- 重复定义
- Object.freeze
- 传值与传址
var/let/const
共同点是全局作用域中定义的变量,可以在函数中使用
var hd = 'wgcehn';
function show() {
return hd;
}
console.log(show());
函数中声明的变量,只能在函数及其子函数中使用
function hd() {
var web = "wgcehn";
function show() {
console.log(web);
}
show(); //子函数结果: wgcehn
console.log(web); //函数结果: wgcehn
}
hd();
console.log(web); //全局访问: hd is not defined
函数中声明的变量就像声明了私有领地,外部无法访问
var web = "wgcehn";
function hd() {
var web = "wgcehn.csdn";
console.log(web); //wgcehn.csdn
}
hd();
console.log(web); //wgcehn
使用 var
声明的变量存在于最近的函数或全局作用域中,没有块级作用域的机制。
没有块作用域很容易污染全局,下面函数中的变量污染了全局环境
function run() {
web = "wgchen";
}
run();
console.log(web); //wgchen
没有块作用作用域时 var
也会污染全局
for (var i = 0; i
关注
打赏