var let const 与 变量提升和函数提升

1. 变量提升函数提升

通常JS引擎会在正式执行之前先进行一次预编译,在这个过程中,首先将变量声明及函数声明提升至当前作用域的顶端,然后进行接下来的处理。

  1. 使用 var 声明,存在变量提升的情况:
console.log(a); // undefined
var a = 1;
console.log(a); // 1

// ======= 实际等效于 =========
var a;
console.log(a); // undefined
a = 1;
console.log(a); // 1
  1. 函数声明式存在函数提升的情况:

    JavaScript 不同于 Java 等强类型语言,是在一个 class 中执行;在遇到函数直接相互调用的情况,都是通过 this 的形式,所以不需要考虑函数提升;而对于JavaScript函数提升就是解决多个函数相互调用的情况,那有些人就说了,可以将函数当参数来解决这种情况,但是这种形式的话,代码的结构就…

console.log(fn); // ƒ fn() {}
function fn() {}
  1. 在同一个作用域声明一个与函数名相同的变量名,函数会覆盖变量名:
console.log(a); // ƒ a() {}
var a = 1;
function a() {};
console.log(a); // 1

// ======= 实际等效于 =========
function a() {};
console.log(a);  // ƒ a() {}
a = 1;
console.log(a); // 1
  1. 函数表达式 的本质,是先声明一个变量,然后将一个匿名函数赋值给这个变量。
console.log(fn); // undefined
var fn = function(){}
console.log(fn); // ƒ (){}

2. letconst

  1. letconst 不存在 变量提升

使用 letconst 声明变量时(当前作用域内),不可以在声明之前使用变量,也就是暂时性死区

console.log(a, b); // Cannot access 'a' before initialization
let a = 1;
const b = 2;
  1. const 声明后,不可以赋值。
var a = 1;
a = 2;
console.log(a); // 2

let b = 1;
b = 2;
console.log(b); // 2

const c = 1;
c = 2;
console.log(c); // Assignment to constant variable.
  1. letconst 存在块级作用域,一般一对 {} 就是一个块级作用域。
{
  var a = 1;
}
console.log(a);

{
  let b = 1;
}
console.log(b); // Uncaught ReferenceError: b is not defined
  1. letconst 不可以重复声明
let a = 1;
let a = 2; // Uncaught SyntaxError: Identifier 'a' has already been declared
  1. 在全局作用域下, letconst 声明的变量不挂载在 window
var a = 1;
let b = 2;
const c = 3;

console.log(window.a); // 1
console.log(window.b); // undefined
console.log(window.c); // undefined

请添加图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值