英文:
let declarations being hoisted to top of their scope
问题
如果我写这个,那么它会打印出未定义:
let a;
console.log(a);
a = 20;
但为什么这会返回一个错误呢?
console.log(a);
let a = 20;
在第二种情况下,a
被提升到顶部,因为在内存分配阶段 JavaScript 不会为 let
分配任何值,所以它返回错误。但是在第一种情况下条件是否也相似呢?为什么在第一种情况下它会打印出未定义呢?
英文:
If I write this then it prints undefined:
let a
console.log(a)
a = 20
but why does this return an error, then?
console.log(a)
let a = 20
a
gets hoisted to the top in case 2 and since JavaScript doesn’t assign any value to let in memory allocation phase it returns error. But isn’t the condition similar in case 1 also? Then why does it print undefined in case 1?
答案1
得分: 2
-
let a
就像let a = undefined
一样 -
故意在声明之前访问使用
let
(或const
或class
)声明的变量是错误的。这就是它的工作方式,因为这样做是最合理的。
绝对不要考虑它作为“内存分配阶段”的概念。
英文:
-
let a
is exactly likelet a = undefined
-
It’s intentionally an error to access a variable declared with
let
(orconst
orclass
) before the declaration. That’s just how it works, because it makes the most sense that way.
Definitely don’t think about it in terms of a “memory allocation phase”.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论