How long will the declared variable last?
When the function to which the variable belongs is processed within the scope,
Variables are also discarded.
Also, in the case of global variables, they always remain, so when can you use them?
I heard that, but is this understanding correct?
About JS.
Also, all variables declared on the class are global, so you can see them from anywhere.
Is it correct to assume that it is the same as the global variable, never discarded, and always exists?
Memory release of JavaScript variables is basically implementation dependent because they are not specified in ECMAScript, but the general idea is that they will remain until they are recovered by the garbage collection (GC).
Specifically, you can infer that "if you no longer refer to the variable within the function scope" will be affected, and the garbage collection will recover from that.
The global variable will remain in memory until the page is unloaded
.
In other words, it is discarded from memory at the time of page transition, Close, Update, Back, or Proceed.
After the function is executed, the implementation drops the local variable from memory at any time.
<script>
(function(x){
console.log(x);
}(1));
// Anonymous function and local variable x are discarded from memory at the end of function execution.
</script>
unless the function scope continues to reference the local variable.
<script>
vargetX=(function(x){// variable x continues to be referenced by the function getX
return function getX() {returnx;};
}(1));
console.log(getX());
</script>
The global variable getX remains in memory until the page is unloaded
.
Because the function getX
continues to reference the variable x
, the variable x
will also remain in memory until the page is unloaded
.
Closures can be easily created by simply nesting functions, so memory savings require an ingenuity not to unnecessarily deepen the hierarchy of functions.
The class has the same idea as above.
If it is not a global variable or a local variable that continues to be referenced by the function scope, it is discarded from memory after execution.
Dear Re:temestack,
© 2024 OneMinuteCode. All rights reserved.