JavaScript中var let const的用法有哪些区别
作者:daixiangcn 时间:2024-05-09 15:06:33
1.重复声明
var支持重复声明,let、const不支持重复声明。
1.1 var
var a = 1;
var a = 2;
console.log(a);
输出结果:
2
1.2 let
let b = 3;
let b = 4;
console.log(b);
输出结果:
Uncaught SyntaxError: Identifier 'b' has already been declared
1.3 const
const c = 5;
const c = 6;
console.log(c);
输出结果:
Uncaught SyntaxError: Identifier 'c' has already been declared
2.变量提升
var支持变量提升,但是只提升声明不提升值。let、const不支持变量提升。
2.1 var
a=2;
console.log(a);
var a = 1;
输出结果:
2
2.2 let
a=2;
console.log(a);
let a = 1;
输出结果:
Uncaught ReferenceError: Cannot access 'a' before initialization at index.html:28
2.3 const
a=2;
console.log(a);
const a = 1;
输出结果:
Uncaught ReferenceError: Cannot access 'a' before initialization at index.html:28
3.暂时性死区
var不存在暂时性死区,let、const存在暂时性死区。
只要作用域内存在let、const,它们所声明的变量或常量就自动“绑定”在这个区域,不再受外部作用域影响。
3.1 var
var a = 1;
function fun() {
console.log(a);
var a = 2;
}
fun();
输出结果:
undefined
3.2 let
let a = 1;
function fun() {
console.log(a);
let a = 2;
}
fun();
输出结果:
Uncaught ReferenceError: Cannot access 'a' before initialization
3.3 conset
let a = 1;
function fun() {
console.log(a);
const a = 2;
}
fun();
输出结果:
Uncaught ReferenceError: Cannot access 'a' before initialization
4. window对象的属性和方法
全局作用域中,var声明的变量、通过function声明的函数,会自动变成window对象的属性和方法。
var a = 1;
function add() { };
console.log(window.a === a);
console.log(window.add === add);
输出结果:
true
true
5.块级作用域
var没有块级作用域,let、const有块级作用域。
使用var
在for循环中定义变量i:
for (var i = 0; i < 3; i++) {
// console.log(i);
}
console.log(i);
输出结果:
3
使用let
在for循环中定义变量i:
for (let i = 0; i < 3; i++) {
// console.log(i);
}
console.log(i);
输出结果:
Uncaught ReferenceError: i is not defined
来源:https://blog.csdn.net/yuanxiang01/article/details/120828446


猜你喜欢
Pycharm无法正常安装第三方库的几条应对方法汇总

Vue Ref全家桶具体用法详解
Python批量修改图片分辨率的实例代码
MySQL安全大讲堂:MySQL数据库安全配置
python opencv进行图像拼接

MySQL存储过程中使用动态行转列

Vue中$forceUpdate()的使用方式

网页制作前台之javascript
Golang中time.After的使用理解与释放问题

vuex 第三方包实现数据持久化的方法
使用Python自动化破解自定义字体混淆信息的方法实例
为vue项目自动设置请求状态的配置方法

python3 pillow模块实现简单验证码

python如何统计序列中元素
python实现bucket排序算法实例分析
python基础教程项目二之画幅好画
python3 QT5 端口转发工具两种场景分析

mysql索引失效的五种情况分析

使用Python进行数独求解详解(二)
