JavaScript吊起了什么?

JavaScript before executing your code parses it, and adds to its own memory every function and variable declarations it finds, and holds them in memory. This is called hoisting.

JavaScript在执行代码之前对其进行解析,并将找到的每个函数和变量声明添加到其自己的内存中,并将它们保存在内存中。 这称为吊装

We have some different behaviors for function declarations and function expressions.

对于函数声明和函数表达式,我们有一些不同的行为。

With function declarations, we can call a function before it’s defined, and our code will work. In the other cases, we’ll have errors.

使用函数声明,我们可以在定义函数之前调用它,然后我们的代码将起作用。 在其他情况下,我们会出现错误。

A general rule of thumb is to always define functions, variables, objects and classes before using them, to avoid surprises.

一般的经验法则是,在使用函数,变量,对象和类之前,请务必对其进行定义,以免引起意外。

Suppose we have a function:

假设我们有一个函数:

function bark() {
  alert('wof!')
}

Due to hoisting, we can technically invoke bark() before it is declared:

由于提升,我们可以从技术上调用bark()然后将其声明为:

bark()
function bark() {
  alert('wof!')
}

With functions, this only happens for function declarations. Like in the case above.

对于函数,这仅在函数声明中发生。 就像上面的情况一样。

Not with function expressions.

没有函数表达式

This is a function expression:

这是一个函数表达式:

bark()
var bark = function() {
  alert('wof!')
}

In this case, the var declaration is hoisted and initialized with undefined as a value, something like this:

在这种情况下,将使用undefined的值来初始化和初始化var声明,如下所示:

var bark = undefined
bark()
bark = function() {
  alert('wof!')
}

Running this code will give you a TypeError: bark is not a function error.

运行此代码将给您带来TypeError: bark is not a function错误。

const and let declarations are hoisted, too, but they are not initialized to undefined like var.

constlet声明也被提升,但是它们没有像var一样被初始化为undefined。

const bark = function() {
  alert('wof!')
}

or

要么

let bark = function bark() {
  alert('wof!')
}

In this case, if you invoke bark() before declaring it, it will give you a ReferenceError: Cannot access 'bark' before initialization error.

在这种情况下,如果在声明之前调用bark() ,它将给您提供ReferenceError: Cannot access 'bark' before initialization错误ReferenceError: Cannot access 'bark' before initialization

The same will happen for any other expression that assigns an object or class to a variable

将对象或类分配给变量的任何其他表达式也会发生同样的情况

Class declarations work like let and const declarations: they are hoisted, but not initialized, and using a class before its declaration will give a ReferenceError: <Class> is not defined error.

类声明的工作方式类似于letconst声明:它们被吊起,但未初始化,并且在声明之前使用类会产生ReferenceError: <Class> is not defined错误。

翻译自: https://flaviocopes.com/javascript-hoisting/

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值