博客
关于我
var 与 const let的区别
阅读量:192 次
发布时间:2019-02-28

本文共 1326 字,大约阅读时间需要 4 分钟。

一、var 变量可以挂载在window上,而const、let不会挂载的window上。

var a = 100;console.log(a,window.a);    // 100 100let b = 10;console.log(b,window.b);    // 10 undefinedconst c = 1;console.log(c,window.c);    // 1 undefined

二、var有变量提升的概念,而const、let没有变量提升的概念

console.log(a); // undefined  ==》a已声明还没赋值,默认得到undefined值var a = 100;
console.log(b); // 报错:b is not defined  ===> 找不到b这个变量let b = 10;console.log(c); // 报错:c is not defined  ===> 找不到c这个变量const c = 10;

其实怎么说呢?

三、var没有块级作用域的概念,而const、let有块级作用于的概念

if(1){    var a = 100;    let b = 10;}console.log(a); // 100console.log(b)  // 报错:b is not defined  ===> 找不到b这个变量
if(1){    var a = 100;            const c = 1;} console.log(a); // 100 console.log(c)  // 报错:c is not defined  ===> 找不到c这个变量

 

四、var没有暂存死区,而const、let有暂存死区

var a = 100;if(1){    a = 10;    //在当前块作用域中存在a使用let/const声明的情况下,给a赋值10时,只会在当前作用域找变量a,    // 而这时,还未到声明时候,所以控制台Error:a is not defined    let a = 1;}

五、let、const不能在同一个作用域下声明同一个名称的变量,而var是可以的

var a = 100;console.log(a); // 100var a = 10;console.log(a); // 10

 

let a = 100;let a = 10;//  控制台报错:Identifier 'a' has already been declared  ===> 标识符a已经被声明了。

六、const相关

当定义const的变量时候,如果值是值变量,我们不能重新赋值;如果值是引用类型的,我们可以改变其属性。

const a = 100; const list = [];list[0] = 10;console.log(list);  // [10]const obj = {a:100};obj.name = 'apple';obj.a = 10000;console.log(obj);  // {a:10000,name:'apple'}

 

转载地址:http://ygni.baihongyu.com/

你可能感兴趣的文章
mySQL和Hive的区别
查看>>
MySQL和Java数据类型对应
查看>>
mysql和oorcale日期区间查询【含左右区间问题】
查看>>
MYSQL和ORACLE的一些操作区别
查看>>
mysql和redis之间互相备份
查看>>
MySQL和SQL入门
查看>>
mysql在centos下用命令批量导入报错_Variable ‘character_set_client‘ can‘t be set to the value of ‘---linux工作笔记042
查看>>
Mysql在Linux运行时新增配置文件提示:World-wrirable config file ‘/etc/mysql/conf.d/my.cnf‘ is ignored 权限过高导致
查看>>
Mysql在Windows上离线安装与配置
查看>>
MySQL在渗透测试中的应用
查看>>
Mysql在离线安装时启动失败:mysql服务无法启动,服务没有报告任何错误
查看>>
Mysql在离线安装时提示:error: Found option without preceding group in config file
查看>>
MySQL基于SSL的主从复制
查看>>
Mysql基本操作
查看>>
mysql基本操作
查看>>
mysql基本知识点梳理和查询优化
查看>>
mysql基础
查看>>
Mysql基础 —— 数据基础操作
查看>>
mysql基础---mysql查询机制
查看>>
MySQL基础5
查看>>