javascript理解_javascript理解吊装

javascript理解

While creating an execution context, The JavaScript engine allocates memory for the variables and functions before executing them. This allows us to do some interesting things like accessing a variable before declaring it.

创建执行上下文时,JavaScript引擎会在执行变量和函数之前为其分配内存。 这使我们可以做一些有趣的事情,例如在声明变量之前访问变量。

As the memory allocation for the variable a has already happened before executing the program line by line, we can access the variable at the very top of the execution context. In the above example, we have two lines of code in the global context. And the fact that only the declarations are hoisted makes the value of a undefined. Initializations won't happen in hoisting and hence it is undefined.

由于在逐行执行程序之前已经为变量a进行了内存分配,因此我们可以在执行上下文的最顶部访问变量。 在上面的示例中,我们在全局上下文中有两行代码。 并且仅悬挂声明的事实构成未定义的值。 吊装不会发生初始化 ,因此未定义。

Image for post

功能声明吊装 (Function Declaration Hoisting)

Like the variable hoisting, the function declarations are also hoisted during the creation phase of an execution context. But unlike the variable hoisting which always gives us undefined, the function declarations allows us to call the function before their declaration.

像变量提升一样,函数声明也在执行上下文的创建阶段被提升。 但是与变量提升始终为我们带来不确定的情况不同,函数声明允许我们在声明之前调用函数。

Image for post

提升功能表达式 (Hoisting In A Function Expression)

Technically a function expression is a variable assigned to a var. So, we already know why we get “func is not a function” error. Because when hoisted, func is not a function but undefined. And, we can not call undefined.

从技术上讲,函数表达式是分配给var的变量。 因此,我们已经知道为什么会出现“ func不是函数”错误。 因为吊装时func不是函数,而是未定义的。 并且,我们不能调用未定义。

Image for post

介绍let和const (Introducing let and const)

The variables declared using let and const simply throw a ReferenceError exception when we try to access before declaring.

当我们在声明之前尝试访问时,使用let和const声明的变量仅引发ReferenceError异常。

Image for post

So, The JavaScript engine won’t hoist the variables declared using let and const? It does. But it won’t initialize the variable.

因此,JavaScript引擎不会提升使用let和const声明的变量吗? 是的 但是它不会初始化变量。

How does a ReferenceError runtime exception (of let and const) be any useful than a silent undefined value (of var)? It is not. It is enforced to make the developers write clean code.

(let和const的)ReferenceError运行时异常比无声的未定义值(var)有什么用? 它不是。 它被强制使开发人员编写干净的代码。

Best Practices:

最佳做法:

  1. Always declare variables at the top of the scope.

    始终在范围的顶部声明变量。
  2. Always initialize a value during declaration.

    在声明期间始终初始化一个值。
  3. Use function expressions instead of function declaration to avoid relying on hoisting.

    使用函数表达式而不是函数声明可以避免依赖提升。

翻译自: https://medium.com/swlh/javascript-understanding-hoisting-4fc566a52a9b

javascript理解

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值