javascript中var、let、const的区别
目录
1.作用域
var 声明的范围是函数作用域,在函数开始时创建,函数结束时销毁;
function test(){
var name="Matt";//局部变量
}
test();
console.log(name);//出错
let 声明的范围是块作用域,块作用域是函数作用域的子集,当块结束时let声明的变量就会被销毁;const 的作用域与let的相同。
if(true){
let age=90;
console.log(age);//90
}
console.log(age);//ReferenceError 未定义
2.提升
提升:把所有的变量声明都拉到函数作用域的顶部。
var声明的变量可以被提升(hoist);
function test(){
console.log(age);
var age=90;
}
test();//输出90
let、const声明的变量不会被提升;
function test(){
console.log(age);
let age=90;
}
test();//ReferenceError
function test(){
console.log(age);
const age=90;
}
test();//ReferenceError
3.重复定义
可以反复多次使用var声明同一个变量;
function test(){
var age=90;
var age=80;
var age=70;
var age=60;
console.log(age);
}
test();// 60
let 不能重复声明同一个变量;const与let相同
function test(){
let age=90;
let age=80;
console.log(age);
}
test();// SyntaxError
4.全局声明
var全局声明的变量会成为Window对象的属性;let、const全局声明的变量不会成为window对象的属性。
var age=90;
console.log(window.age); // 90
let age=80;
console.log(window.age); // undefined
const age=70;
console.log(window.age);// undefined
5.let与const
let与const 基本相同,唯一区别是 用const声明变量时必须初始化变量,且尝试修改const声明的变量会导致运行时错误。
6.var全局
在函数内部定义变量时省略var操作符,可以定义一个全局变量:
function test(){
name="Matt";//全局变量
}
test();
console.log(name);// Matt