博客
关于我
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底层概述—3.InnoDB线程模型
查看>>
MySQL底层概述—4.InnoDB数据文件
查看>>
MySQL底层概述—5.InnoDB参数优化
查看>>
MySQL底层概述—6.索引原理
查看>>
MySQL底层概述—7.优化原则及慢查询
查看>>
MySQL底层概述—8.JOIN排序索引优化
查看>>
MySQL底层概述—9.ACID与事务
查看>>
Mysql建立中英文全文索引(mysql5.7以上)
查看>>
mysql建立索引的几大原则
查看>>
Mysql建表中的 “FEDERATED 引擎连接失败 - Server Name Doesn‘t Exist“ 解决方法
查看>>
mysql开启bin-log日志,用于canal同步
查看>>
MySQL开源工具推荐,有了它我卸了珍藏多年Nactive!
查看>>
MySQL异步操作在C++中的应用
查看>>
MySQL引擎讲解
查看>>
Mysql当前列的值等于上一行的值累加前一列的值
查看>>
MySQL当查询的时候有多个结果,但需要返回一条的情况用GROUP_CONCAT拼接
查看>>
MySQL必知必会(组合Where子句,Not和In操作符)
查看>>
MySQL必知必会总结笔记
查看>>
MySQL快速入门
查看>>
MySQL快速入门——库的操作
查看>>