博客
关于我
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经常使用技巧
查看>>
mysql给root开启远程访问权限,修改root密码
查看>>
mysql给账号授权相关功能 | 表、视图等
查看>>
MySQL缓存使用率超过80%的解决方法
查看>>
Mysql缓存调优的基本知识(附Demo)
查看>>
mysql编写存储过程
查看>>
mysql网站打开慢问题排查&数据库优化
查看>>
mysql网络部分代码
查看>>
mysql联合索引 where_mysql联合索引与Where子句优化浅析
查看>>
mysql联合索引的最左前缀匹配原则
查看>>
MySQL聚簇索引
查看>>
mysql自动化同步校验_Shell: 分享MySQL数据同步+主从复制自动化脚本_20190313_七侠镇莫尛貝...
查看>>
Mysql自增id理解
查看>>