let,const 与 var的区别

1. let和var是声明变量的,const是声明常量的

2. let和const不存在变量提升

3. let 和const不允许重复声明

4. 块级作用域

  块级作用域存在于

  •  const和let
  •    花括号{}
if(true) {
  let s = 1; 
 const j = 2 } console.log(s)
// 报错 s is not defined
console.log(j) // 报错 j is not defined
 

5. let和const存在暂时性死区

  

let s = 1;
let Printing = function() {
    console.log(s); // 报错 s is not defined
    let s = 2;  
}

6. 顶层对象中的let 和 const 

从es6开始,全局变量(例如:import、class、let、const声明的)将逐步与顶层对象的属性隔离。

//顶层对象中的var
var foo = {name: 'lee', age: 18};
cosole.log(foo === window.foo);  //true
console.log(window.foo);   //{name: 'lee', age: 18}

//顶层对象中的let和const
let obj = {height: 182, weight: 140};
const mt = {msg:'hello’};

console.log(obj === window.obj);  //false
console.log(window.obj);   //undefined

console.log(mt === window.mt);   //false
console.log(window.mt);      //undefined

tip:

const声明的常量只是指针不能改变,如果const声明的是引用类型,我们是可以改变其中的值的

const arr = [1,2,3];
arr.push(4);
console.log(arr);  [1,2,3,4]

如何找到顶层对象

//方法一
(typeof window  !== 'undefined'
 ? window
  : (typeof process === 'object' &&
     typeof require === 'function' &&
     typeof global === 'object' )
    ? global 
    : this)

//方法二
var getGlobal = function(){
  if(typeof self !== 'undefined') {return self;}
  if(typeof window !== 'undefined') {return window;}
  if(typeof global !== 'undefined') {return global;}
  throw new Error('unable to locate global object');
};

  

  

猜你喜欢

转载自www.cnblogs.com/zhangshilei/p/12188401.html
今日推荐