声明和定义的变量之间是否有任何区别 [英] Is there any difference between declared and defined variable

查看:91
本文介绍了声明和定义的变量之间是否有任何区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试逐一在控制台中编写以下行

I try writing the following lines in the console one by one

let x = y //throws error "Uncaught ReferenceError: y is not defined"
console.log(x) //throws error "ReferenceError: x is not defined"
let x = 3; //gives error "Uncaught SyntaxError: Identifier 'x' has already been declared"
x = 3 //ReferenceError: x is not defined

现在的问题是,如何变量未定义同时声明。两者之间有什么区别吗?

Now problem is that how can be a variable not defined and has been declared at the same time. Is there any difference between both.

推荐答案

A const 变量只能声明一次 - 也就是说,当您在范围内有 let< variableName> 时,您已声明该范围内的< variableName> ,并且无法在该范围内再次声明。

A let or const variable can only be declared once - that is, when you have let <variableName> in a scope, you have declared <variableName> in that scope, and cannot declare it again in that scope.

来自先前关联的问题


当有分配时,首先解析右侧;如果右侧抛出错误,它永远不会到达左侧,并且使用let声明的变量永远不会被正确初始化;它将永远停留在非军事区/临时死区

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

你不能重新声明已经声明的变量,即使在初始化期间尝试的分配引发了错误。

You can't re-declare a variable that's already been declared, even though the attempted assignment during initialization threw an error.


但是在第4行,x = 3应该进行正确的分配,它应该删除来自TDZ的x。但那也失败了。我无法理解

But on line 4, x=3 should do a proper assignment and it should remove x from TDZ. But that also fails. I fail to understand that

变量初始化后(例如,让x 运行),可以将其分配给。但就像你无法在 c c> c>初始化之前分配变量一样,你也无法在以后的初始化时分配给变量没有成功完成:

After a variable has been initialized (for example, the let x runs), it can be assigned to. But just like you can't assign to a variable before its let initialization, you also can't assign to a variable later, when its initialization did not complete successfully:

x = 'foo';
let x = 'bar';

错误:


未捕获的ReferenceError:x未定义

Uncaught ReferenceError: x is not defined

这是同类的当您尝试时在控制台中发生的事情:

Which is the same sort of thing that happens in the console when you try:

let x = y
// Uncaught ReferenceError: y is not defined
// x has not been initialized, so the next line throws:
x = 'foo'
// Uncaught ReferenceError: x is not defined

x 仍未初始化,因此错误相同。

x still has not been initialized, so the error is the same.

遇到这种事情的是非常奇怪,但是 - 你只能在控制台中看到它。在普通脚本中,抛出的错误将阻止进一步执行,并且变量名称永远未被初始化的事实不值得担心。

Encountering this sort of thing is pretty odd, though - you only see it in the console. In normal scripts, a thrown error will prevent further execution, and the fact that a variable name remains uninitialized forever is not something to worry about.

这篇关于声明和定义的变量之间是否有任何区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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