


Detailed explanation of the difference between JavaScript basic data types and reference types
Two days ago, I saw kraaas
’s article about the difference between basic data types and reference types. I thought it was very well written, so I thought about building on it. In addition to some knowledge points and understandings that I usually see, I have the following article
js basic data types:
js basic data types include: undefined , null, number, boolean, string. Basic data types are accessed by value, which means we can operate on the actual values stored in variables
1. The values of basic data types are immutable
No method can change the value of a basic type, such as a string:
var name = "change"; name.substr();//hang console.log(name);//change var s = "hello"; s.toUpperCase()//HELLO; console.log(s)//hello
Through these two examples, we will find that the value of the originally defined variable name has never changed, and calling The substr() and toUpperCase() methods return a new string, which has nothing to do with the originally defined variable name
Some people may have the following questions, look at the code:
var name = "change"; name = "change1"; console.log(name)//change1
It looks like the value of name has "changed". In fact, var name = "change", the basic type here is string, which is "change", the "change" here cannot be changed, and name just points to "change" A pointer, the pointing of the pointer can be changed, so you can name = "change1". At this time, the name points to "change1". Similarly, the "change1" here cannot be changed.
That is to say, here The change you think is just "a change in the pointer's pointing"
The basic type here refers to "change", not name, you must distinguish clearly
2. Basic data types cannot add attributes and methods
var p = "change"; p.age = 29; p.method = function(){console.log(name)}; console.log(p.age)//undefined console.log(p.method)//undefined
Through the above code, we know that properties and methods cannot be added to basic types, and it also proves again that basic types are immutable
3. The assignment of basic data types is simple assignment
If you assign a value of a basic type from one variable to another, a new value will be created on the variable object and then copied to the location allocated for the new variable
var a = 10; var b = a; a++; console.log(a)//11 console.log(b)//10
In the above code, the value saved in a is 10. When the value of a is used to initialize b, the value 10 is also saved in b. But the 10 in b and the 10 in a are completely independent. The value in b A copy of the value in knowledge a. So these two variables can participate in any operation without affecting each other. As shown below:
4. The comparison of basic data types is value Comparison
var person1 = '{}'; var person2 = '{}'; console.log(person1 == person2); // true
5. The basic data type is stored in the stack area
If there are the following basic types of variables:
var name = "jozo"; var city = "guangzhou"; var age = 22;
Then its storage structure is as follows :
The stack area includes the identifier of the variable and the value of the variable
js reference type:
In addition to the above basic In addition to types, there are reference types, which can also be said to be objects, such as: Object, Array, Function, Data, etc.
1. The value of a reference type can be changed
var o = {x:1}; o.x = 2;//通过修改对象属性值更改对象 o.y = 3;再次更改对象,给它增加一个属性 var a = [1,2,3]; a[0] = 0;//更改数组的一个元素 a[3] = 4;//给数组增加一个元素
2. Reference types can add properties and methods
var person = {}; person.name = "change"; person.say = function(){alert("hello");} console.log(person.name)//change console.log(person.say)//function(){alert("hello");}
3. The assignment of reference types is object references
First look at the following code:
var a = {}; var b= a; a.name = "change"; console.log(a.name)//change; console.log(b.name)//change b.age = 29; console.log(a.age)//29 console.log(b.age)//29
When assigning a value from one variable to another variable When referencing a value of type, the value of the object stored in the variable will also be copied to the space allocated for the new variable. What the reference type saves in the variable is the address of the object in the heap memory, so, with Different from the simple assignment of basic data types, the copy of this value is actually a pointer, and this pointer points to an object stored in the heap memory. Then after the assignment operation, both variables save the same object address, and these two The address points to the same object. Therefore, changing any of the variables will affect each other
Their relationship is as shown below:
Therefore, the reference type Assignment is actually the assignment of the address pointer of the object stored in the stack area, so two variables point to the same object, and any operations will affect each other.
4. The comparison of reference types is the comparison of references
var person1 = {}; var person2 = {}; console.log(person1 == person2)//false
Why do the two objects look exactly the same, but are not equal?
Because the comparison of reference types is a comparison of references, in other words, it is to compare whether the addresses of the two objects stored in the stack area pointing to the heap memory are the same. At this time, although p1 and p2 appear to be the same "{}", but the addresses pointed to heap memory they save in the stack area are different, so the two objects are not equal
5. 引用类型是同时保存在栈区和堆区中的
引用类型的存储需要在内存的栈区和堆区共同完成,栈区保存变量标识符和指向堆内存的地址
假如有以下几个对象:
var person1 = {name:"change1"}; var person2 = {name:"change2"}; var person3 = {name:"change3"};
则这三个对象在内存中保存的情况如下图:
基本包装类型(包装对象):
先看下以下代码:
var s1 = "helloworld"; var s2 = s1.substr(4);
上面我们说到字符串是基本数据类型,不应该有方法,那为什么这里s1可以调用substr()呢?
通过翻阅js权威指南第3.6章节和高级程序设计第5.6章节我们得知,ECMAScript还提供了三个特殊的引用类型Boolean,String,Number.我们称这三个特殊的引用类型为基本包装类型,也叫包装对象.
也就是说当读取string,boolean和number这三个基本数据类型的时候,后台就会创建一个对应的基本包装类型对象,从而让我们能够调用一些方法来操作这些数据.
所以当第二行代码访问s1的时候,后台会自动完成下列操作:
创建String类型的一个实例;// var s1 = new String(“helloworld”);
在实例上调用指定方法;// var s2 = s1.substr(4);
销毁这个实例;// s1 = null;
正因为有第三步这个销毁的动作,所以你应该能够明白为什么基本数据类型不可以添加属性和方法,这也正是基本装包类型和引用类型主要区别:对象的生存期.使用new操作符创建的引用类型的实例,在执行流离开当前作用域之前都是一直保存在内存中.而自动创建的基本包装类型的对象,则只存在于一行代码的执行瞬间,然后立即被销毁。
以上就是JavaScript 基本数据类型和引用类型的区别详解 的内容,更多相关内容请关注PHP中文网(www.php.cn)!
相关文章:

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

When a generic function handles pointer types in Go, it will receive a reference to the original variable, allowing the variable value to be modified. Reference types are copied when passed, making the function unable to modify the original variable value. Practical examples include using generic functions to compare strings or slices of numbers.

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).
