What causes the different behaviors between “var” and “let” when assign them a returned value of a function which throws an error
请在下图中找到代码。1。将实际引发错误的函数的返回值赋给使用关键字"let"声明的变量"withlet"。2。调用"Withlet",发生错误:"未定义Withlet"。三.尝试使用"let"断言"Withlet",错误表明已声明"Withlet"。
但是"var"的悖论并不存在(请在下图中找到)。
我很好奇是什么导致了这两种情况下的不同行为。"未定义的"和"已声明的"描述同一个变量是非常复杂的。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | 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 //:1:1 //(anonymous) @ VM2484:1 withVar //undefined let withLet = 'sth' //VM2520:1 Uncaught SyntaxError: Identifier 'withLet' has already been //declared //at :1:1 //(anonymous) @ VM2520:1 withVar = 'sth' //"sth" |
截图:
提升
1 | var withVar = (function() {throw 'error!'})() |
被解释器解析为
1 2 | var withVar; withVar = (function() {throw 'error!'})() |
当
这有点奇怪,因为代码是在控制台中运行的——通常情况下,JS运行在一个