JavaScript

JavaScript Learning : Variables, Scope, and Memory

JavaScript Learning : Variables, Scope, and Memory, someone asked me to explain?

These types occupy a fixed size of space in memory, and their values are stored in the stack space, which we access by value.

Reference type value: Object

If you assign a value of a reference type, you must allocate space for the value in heap memory. Because the value size is not fixed, they cannot be saved to the stack memory. However, the memory address size is fixed, so the memory address can be stored in the stack memory.

When querying a variable of a reference type, the memory address is first read from the stack, and then the value in the heap is found by the address, called by reference.

Detecting basic types, usually, we don't know if it is an object, but we want to know what type of object it is, because the array is also object, and null is also object, then we should use the instanceof operator to view.

Extension: Usually js detects a variable type, which is detected by typeof, and can only output specific data types.

<script type="text/javascript">
    var box = [1, 2, 3];
    alert(box instanceof Array);
    var box2 = {};
    alert(box2 instanceof Object);
    var box3 = /g/;
    alert(box3 instanceof RegExp);
    var box4 = new String('cai')
    alert(box4 instanceof String);
</script>

Scope:

Each function will create its own execution environment when it is called. When it is executed, the environment of the function will be pushed to the environment stack to execute, and after execution, it will exit in the environment and give control to the upper level. Execution environment

When the code is executed in the previous environment, something called a domain chain is formed. Its purpose is to ensure orderly access to variables and functions that have access rights in the execution environment.

Post your comments / questions