This article brings you an analysis of the difference between basic data types and reference types in JavaScript. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
There are only 6 types in JS. Among them, there are 5 basic data types: string, number, boolen, null, and undefined. There is one reference type, which is object. Object is A large complex, except for the five basic data types in JS, everything else is an object.
var a = 100; var b = a; a++ console.log(a)//101 console.log(b)//100
var obj1 = new object(); var obj2 = new object(); obj1.age = 18; obj2 = obj1; obj1.age++ console.log(obj1.age)//19 console.log(obj2.age)//19
You can see it above Both examples change the value. The basic data type that is assigned will not change, but the reference that is assigned will also change accordingly. So why is this? It's actually very simple, and can be summarized in one sentence: because basic data types store values, while reference types store addresses.
Explanation example
When a new variable is created, it will be stored on the stack. If it is an object, an area will be divided into another larger heap, then in The object stored on the stack is the address in the heap.
Basic data types
As shown above, basic data types store values directly on the stack. When a changes time, b will not change, because b is only equal to the value of a and has nothing to do with a.
Reference type (object)
What is stored in obj1 and obj2 are addresses, and obj2 is not equal to the value of obj1. It is equal to the address of obj1 stored in the heap, so when the content in the address changes, the content of obj2 will also change. As long as a new object is created, a new area will be opened in the heap to store the object's properties, methods, etc.
Related recommendations:
Learn the basic types and reference types of javascript with me_javascript skills
A brief analysis of the basics of JavaScript Types and Reference Types_Basic Knowledge
The above is the detailed content of Analysis of the difference between basic data types and reference types in JavaScript. For more information, please follow other related articles on the PHP Chinese website!