简体   繁体   English

Javascript变量内存分配

[英]Javascript variable memory allocation

At what stage is the memory allocated to variables in Javascript wrt declaration and initialisation?在 Javascript wrt 声明和初始化中分配给变量的内存是在哪个阶段?

console.log(a); // Prints undefined
var a;
a = 20;

For the above snippet, a = undefined even before the code execution starts.对于上面的代码片段,即使在代码执行开始之前, a = undefined 也是如此。 Does that imply that memory has been allocated during the creation of the variable environment with no value ( undefined )?这是否意味着在创建没有值( undefined )的变量环境期间分配了内存? If yes, during code execution phase, when the JS engine comes across a = 20 does a new memory block gets allocated to 20 to which a points ?如果是,在代码执行阶段,当 JS 引擎遇到a = 20是否将新的内存块分配给 a 指向的 20 ?

It's called hoisting.这叫做吊装。

From the MDN Web Docs documentation on hoisting :来自关于提升MDN Web Docs 文档

the interpreter allocates memory for variable and function declarations prior to execution of the code解释器在执行代码之前为变量和函数声明分配内存

Think of it as if all your variables, declared as var in future, are first read and set to undefined .把它想象成好像你所有的变量,在未来声明为var ,首先被读取并设置为undefined The changes on the variable value later will be assigned to the same variable.稍后对变量值的更改将分配给同一个变量。

 console.log(a); // undefined var a; a = 20; console.log(a); // 20

Note that, you are only able to do it with var -- let and const are read only at the their declaration point.请注意,您只能使用var来执行此操作—— letconst在它们的声明点是只读的。

console.log(b); // ReferenceError: b is not defined


console.log(c); // ReferenceError: c is not defined
let c = 1;


console.log(d); // ReferenceError: d is not defined
const d = 1;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM