博客
关于我
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进入数据库
查看>>
mysql进阶 with-as 性能调优
查看>>
mysql进阶-查询优化-慢查询日志
查看>>
wargame narnia writeup
查看>>
MySQL进阶篇SQL优化(InnoDB锁问题排查与解决)
查看>>
Mysql进阶索引篇03——2个新特性,11+7条设计原则教你创建索引
查看>>
mysql远程连接设置
查看>>
MySql连接出现1251Client does not support authentication protocol requested by server解决方法
查看>>
Mysql连接时报时区错误
查看>>
MySql连接时提示:unknown Mysql server host
查看>>
MySQL连环炮,你扛得住嘛?
查看>>
mysql逗号分隔的字符串如何搜索
查看>>
MySQL通用优化手册
查看>>
Mysql通过data文件恢复
查看>>
MYSQL遇到Deadlock found when trying to get lock,解决方案
查看>>
MYSQL遇到Deadlock found when trying to get lock,解决方案
查看>>
mysql部署错误
查看>>
MySQL配置信息解读(my.cnf)
查看>>
Mysql配置文件my.ini详解
查看>>
MySQL配置文件深度解析:10个关键参数及优化技巧---强烈要求的福利来咯。
查看>>