01let和const

简介: 01let和const

1.1 let


作用

声明局部变量


特性

不存在变量提升

不能重复声明

不作为window属性

块级作用域

暂时性死区(声明前不能使用)


1.2 const


作用

生成常量


特性

与let一致


globalThis 对象


Es5模块中的this是window

Es6模块中的this是undefined

函数中的this,如果函数不是作为对象的方法执行,而是单纯作为函数执行,this会指向顶层对象,但是严格模式下this会返回undefined

不管是严格模式,还是普通模式,new Function(‘return this’)(),总是会返回全局对象。但是,如果浏览器用了 CSP(Content Security Policy,内容安全策略),那么eval、new Function这些方法都可能无法使用。


获取顶层对象的方法

// 方法一
(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');
};


相关文章
|
10月前
|
安全 编译器 C++
对C++中const的说明
对C++中const的说明
44 0
详解const
C++中提供了很多关键字赋予一些东西特殊的函数,比如const、override、final等,本文将从有类和无类两个方面详细介绍const的相关用法于注意事项。剩下的等我这几天加班加点更新吧!
|
8月前
const
const
164 0
|
11月前
const int*p 与 int const *p与 int * const p与const int * const p的区别(有明显对比,超级详细,超级好记)
当只有一个const并且const在*左边时: (const int*p 与 int const *p,)*p的值不能改,但是p(地址)能改.我们可以看到第一,三张图片第五行*p下面有红线表示错误.而第二,四张没有红线的地方表示正确.所以我们可知道const int*p 与 int const *p是相同的只是书写方法不同.
52 0
|
12月前
|
C++
C++ int const 和 const int 的区别
C++ int const 和 const int 的区别
126 0
|
存储 安全 编译器
const 的使用
const 是"constant"的缩写,意思是永恒不变的,它定义的是只读变量的关键字,或者说是定义常变量的关键字。
97 0
|
JavaScript 前端开发
let和const
let和const
|
JavaScript 前端开发
一个非常常见的问题:var、let和const
在ECMAScript中,有3个关键字可以用于声明变量。分别是:var、let和const。其中,var在所有ECMAScript都是可以使用的,但是let和const需要在ECMAScript6及其以上版本才可以使用。
102 0
一个非常常见的问题:var、let和const