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
.
const
和let
声明也被提升,但是它们没有像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.
类声明的工作方式类似于let
和const
声明:它们被吊起,但未初始化,并且在声明之前使用类会产生ReferenceError: <Class> is not defined
错误。