初始化与分配 [英] Initialization vs assignment
问题描述
术语初始化和赋值似乎可以互换使用。我做了一些搜索,似乎技术上可能有所不同。我的理解是,在变量的上下文中,当JavaScript引擎使其可用时,变量被初始化,并且赋值(无论是否明确地完成[如 let foo = 1;
]或JavaScript引擎,如下例所示)是实现此目的的一种方法。
The terms "initialization" and "assignment" seem to be used interchangeably. I did some searching and it seems that there might technically be a difference. My understanding is that, in the context of variables, a variable is initialized when the JavaScript engine makes it available for use, and assignment (whether done explicitly [as in let foo = 1;
] or by the JavaScript engine, as in the following example) is one way to achieve this.
let foo;
console.log(foo); // undefined (initialization and assignment?)
我的理解是否正确?另外(如果是这样),在初始化期间实际发生什么以使变量可用?
Is my understanding correct? Also (if so), what actually occurs during initialization to make the variable available?
推荐答案
TLDR:
{ // declaration (hoisted)
// Temporal deadzone
let foo; // declaration and initialization to undefined
foo = 1; // assignment
}
稍微长一点:
声明
Declaration
声明变量意味着我们在当前范围内保留标识符。在javascript声明被提升时,这意味着当变量所在的范围变得可见时它被声明(它所处的块被执行)。但是你现在无法访问该变量,因为它在
Declaring a variable means that we reserve the identifier at the current scope. In javascript declarations are hoisted, that means that it gets declared when the scope the variable is in gets visible (the block it is in gets executed). However you cannot access that variable now as it is in
这是特定部分范围开头和初始化之间的代码。试图在此处访问变量会导致错误。
This is a specific part of the code that is between the beginning of the scope and the initialization. Trying to access the variable here results in an error.
初始化
Initialization
初始化发生在您声明变量的行中。它将为变量分配一个值,并使其可供访问。例如:
The initialization takes place in the line were you declared the variable. It will assign a value to the variable and will make it available for access. This for example:
let foo;
将 foo
初始化为 undefined
,
let foo = 2;
将 foo
初始化为 2
。
作业
Assignment
...只是意味着您更改变量的值。 javascript中的所有作业都使用 =
。初始化基本上只是第一个暗示。
...just means that you change the value of a variable. All assignments in javascript use =
. The initialization is basically just the first assinment.
上面的解释不适用于用 var
,所以只是不要使用 var
来避免混淆:)
The explanation above does not apply to variables declared with var
, so just don't use var
to avoid confusion :)
这篇关于初始化与分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!