prologue

First look at a classic JS storage problem, to a tense and stimulating brain to eat chicken war:

var a = {n:1};
a.x = a = {n:2};
console.log(a.x);
console.log(a); ,Copy the code

Ask the output? I think we all have the answer… The results are obviously interesting,

Here have part of the audience friends asked, this special meow zha undefined? Isn’t that an assignment? Before you swear, read on:


To explore the moment

Let’s change the code like this:

a.x = a = {n:2};   ---- >  a = a.x = {n:2};
Copy the code

The results are obviously consistent, whether you assign a first or you assign A.x first. After looking up some data, we know that in this equation. Is the highest priority,

So the idea is:

JS stores variables on the stack and objects on the heap.

  1. The first line of code: a pointer to the stack;
  2. A.x = a = {n:2}; The variable pair X in heap 1 points to heap 2 {n:2}, and then a is assigned a={n:2}. The pointer to a is changed to point to heap 2, and then heap 1 is not pointed to and is collected by GC, so the output a.x is underfinde and a is {n:2};

Understanding the above code requires only a little understanding of js variable storage:

As you know, there are two types of variable types in JavaScript. One is the basic data type and the other is the reference type.

The two data types are stored differently in JS.

In addition, memory is divided into stack area and heap area, and then in JS developers can not directly operate the heap area, the heap area data is operated by the JS engine, then what is the difference between the two data storage?


Reveal the moment

One picture tells you:

The definition of a variable in JS consists of three parts in memory:

  • Variable markers (such as Str in the figure above, variable markers are stored in the stack of memory)
  • The value of a variable (for example, the value of Str, the address of the object obj1 pointing to the heap, which is also stored on the stack)
  • Objects (such as object 1 or object 2 in the figure above, which are stored in the heap)

That is, for basic data types, only the stack of memory is used. Let’s make one more interesting change:

var a = {n:1};
var b = a;
a.x = a = {n:2};
console.log(a.x);
console.log(a);
console.log(b);
console.log(b.x);
Copy the code

As you can see, we did not operate on b but b.x is equal to {n:2}, which is an manipulated value. As we know above, b points to heap 1, so the heap is not collected, but is displayed ~

From such a simple example, do you have a new understanding of JS storage mechanism

Welcome the boss’s correction and all kinds of ravage to teach ~~~