导致“var”之间的不同行为的原因是什么?和“让”为它们分配一个抛出错误的函数的返回值 [英] What causes the different behaviors between "var" and "let" when assign them a returned value of a function which throws an error

查看:118
本文介绍了导致“var”之间的不同行为的原因是什么?和“让”为它们分配一个抛出错误的函数的返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请在下图中找到代码。
1.将函数的返回值分配给使用关键字'let'声明的变量'withLet',实际抛出错误。
2.调用'withLet',发生错误:'withLet未定义'。
3.尝试使用'let'断言'withLet',错误显示'withLet'已经被声明。

Please find the code in the image below. 1. Assign the returned value of a function, which throws an error actually, to the variable 'withLet' that declared by using keyword 'let'. 2. call 'withLet', an error occured: 'withLet is not defined'. 3. try to assert 'withLet' using 'let', an error shows that 'withLet' has already been declared.

但矛盾不存在对于'var'(请参见下图)。

But the paradox is not exist for 'var' (Please find in the following image).

我很好奇是什么导致了这两种情况之间的不同行为。非常有线,'未定义''已经声明'描述相同的变量。

I'm curious about what caused the different behaviors between these two situations. It's quite wired that 'not defined' an 'already been declared' describe a same variable.

let withLet = (function() {throw 'error!'})()
var withVar = (function() {throw 'error!'})()
//VM2470:1 Uncaught error!
//(anonymous) @ VM2470:1
//(anonymous) @ VM2470:1
withLet
//VM2484:1 Uncaught ReferenceError: withLet is not defined at 
//<anonymous>:1:1
//(anonymous) @ VM2484:1
withVar
//undefined
let withLet = 'sth'
//VM2520:1 Uncaught SyntaxError: Identifier 'withLet' has already been 
//declared
//at <anonymous>:1:1
//(anonymous) @ VM2520:1
withVar = 'sth'
//"sth"

屏幕截图:

推荐答案

声明 var 变量被提升 - 变量名称初始化被提升到包含函数的顶部(或者,如果没有功能,则到外部块的顶部)。所以

Declarations of var variables get hoisted - the variable name initialization gets hoisted to the top of the containing function (or, if no function, to the top of the outer block). So

var withVar = (function() {throw 'error!'})()

由解释器解析为

var withVar;
withVar = (function() {throw 'error!'})()

同样不适用于 - 变量初始化为让__ 直线运行。在分配时,首先解析右侧;如果右侧抛出错误,它永远不会到达左侧,并且用声明的变量让永远不会被正确初始化;它将永远留在非军事区/时间死区,所以尝试重新分配它会引发错误。

The same is not true for let - let variables become initialized once the let __ line runs. When there's assignment, the right-hand side is parsed first; if the right-hand side throws an error, it never gets to the left-hand side, and the variable declared with let never gets properly initialized; it'll stay in the demilitarized zone / temporal dead zone forever, so trying to reassign it throws an error.

这有点奇怪,因为代码是在控制台中运行的 - 通常,JS在一个内部运行< script> 标记,如果发生此类错误,通常将不再运行代码,以及使用<$声明的变量这一事实c $ c>让不再可重新分配是您最不担心的事情。

It's kind of weird because the code is being run in the console - ordinarily, JS runs inside a <script> tag, and if such an error occurs, usually no more code will run, and the fact that a variable declared with let is no longer reassignable is the least of your worries.

这篇关于导致“var”之间的不同行为的原因是什么?和“让”为它们分配一个抛出错误的函数的返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆