javascript使用_了解使用javascript进行吊装

javascript使用

In JavaScript, Hoisting is the default behavior where variables and function declarations are moved to the top of their scope before code execution.

在JavaScript中,提升是默认行为,在代码执行之前,变量和函数声明会移至其作用域的顶部。

No Matter where function and variable are declared, it moved up top on their own scope. Doing this, it allows us to call functions before even writing them in our code.

在函数和变量没有声明的地方都没有问题,它在自己的作用域内向上移动。 这样一来,我们甚至可以在代码中编写函数之前就调用它们。

Image for post

How interpreter sees the above code:

解释器如何看上面的代码:

Image for post

We Know, In JavaScript, when we have a variable that is not defined then it occurs an undefined error. So in the above example, JavaScript only hoists the declarations part and we got an undefined error.

我们知道,在JavaScript中,当我们有一个未定义的变量时,它将发生未定义的错误。 因此,在上面的示例中,JavaScript仅提升了声明部分,而我们得到了未定义的错误。

It’s important to keep in mind that, JavaScript only hoists declarations, not the initializations.

重要的是要记住,JavaScript仅提升声明,而不初始化。

let us take another example,

让我们再举一个例子

Image for post

why this time we got a ReferenceError? Because of trying to access a previously undeclared variable And remember JavaScript only hoists declarations. So Initialisation can’t be hoisted and we got an error.

为什么这次我们遇到ReferenceError? 因为尝试访问以前未声明的变量,所以请记住JavaScript仅提升声明。 因此初始化无法执行,我们遇到了错误。

ES6: Let Keyword

ES6:让关键字

Image for post

Like before, for the var keyword, we expect the output to be undefined. But this time we got a reference error. That Means let and const variables not hoisted? The answer is Variables declared with let are still hoisted, but not initialized, inside their nearest enclosing block. If we try to access it before initializing will throw ReferenceError due being into Temporal Dead Zone.

像以前一样,对于var关键字,我们希望输出未定义。 但是这次我们得到了参考错误。 那意味着不让let和const变量挂起吗? 答案是,用let声明的变量仍在其最近的封闭块中悬挂,但未初始化。 如果我们尝试在初始化之前访问它,则会由于出现临时死区而引发ReferenceError。

Hoisting functions

起重功能

Like variables, the JavaScript engine also hoists the function declarations. And it allows us to call functions before even writing them in our code.

像变量一样,JavaScript引擎也可以提升函数声明。 而且它允许我们在甚至将它们编写到代码中之前就调用函数。

Image for post

Hoisting in function expressions are not allowed at all. If you doing this you will get an error.

根本不允许在函数表达式中进行提升。 如果这样做,您将得到一个错误。

Image for post

I hope this lesson provides a clear understands of how Hoisting works in JavaScript. Hopefully, you learned something today. Happy Coding.

我希望本课能使您清楚地了解到提升在JavaScript中的工作方式。 希望您今天学到了一些东西。 编码愉快。

翻译自: https://medium.com/@abdullahimran/understanding-hoisting-in-javascript-b82c3fde978d

javascript使用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值