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

标签:JavaScript,var,let,const
0
投稿

猜你喜欢

  • Pycharm无法正常安装第三方库的几条应对方法汇总

    2021-07-18 00:59:52
  • Vue Ref全家桶具体用法详解

    2024-04-27 15:49:06
  • Python批量修改图片分辨率的实例代码

    2023-01-30 01:59:10
  • MySQL安全大讲堂:MySQL数据库安全配置

    2009-10-18 11:24:00
  • python opencv进行图像拼接

    2022-09-10 16:13:01
  • MySQL存储过程中使用动态行转列

    2024-01-16 22:03:16
  • Vue中$forceUpdate()的使用方式

    2024-06-05 09:15:53
  • 网页制作前台之javascript

    2013-07-23 08:32:59
  • Golang中time.After的使用理解与释放问题

    2024-04-25 13:20:08
  • vuex 第三方包实现数据持久化的方法

    2024-04-30 10:34:56
  • 使用Python自动化破解自定义字体混淆信息的方法实例

    2022-05-24 20:15:34
  • 为vue项目自动设置请求状态的配置方法

    2024-04-30 10:44:26
  • python3 pillow模块实现简单验证码

    2021-07-04 11:10:44
  • python如何统计序列中元素

    2022-03-04 16:32:16
  • python实现bucket排序算法实例分析

    2023-09-17 17:54:07
  • python基础教程项目二之画幅好画

    2023-09-10 05:06:32
  • python3 QT5 端口转发工具两种场景分析

    2023-04-03 10:34:46
  • mysql索引失效的五种情况分析

    2024-01-24 16:27:22
  • 使用Python进行数独求解详解(二)

    2023-02-25 22:33:41
  • Golang 删除文件并递归删除空目录的操作

    2024-02-16 04:33:06
  • asp之家 网络编程 m.aspxhome.com