


A brief analysis of JavaScript basic types and reference types_Basic knowledge
For JavaScript types, it can be simply summarized as: compared to strongly typed languages, it is a weak (loose) typed language; there are basic types and reference types, and the difference between them is that there is a fixed space in the stack memory. , an unfixed space is saved in heap memory and a pointer to the implementation location is saved in stack memory.
Many books on the market have a lot of space to talk about it. This article will cover several aspects that may require you to have some basic understanding of JavaScript, especially JavaScript types. If you still don’t understand it, you can pick up a book about JavaScript and read it before reading this article.
1. Basic types and reference types
1. Basic types: Undefined/Null/Boolean/Number/String
2. Reference types: Object/Array/Function/Date/RegExp/Error/Map/Set…
Why haven’t the reference types been enumerated? Because it’s enough for you to know this much, at least for this article I’m talking about. Others may be rarely used, and even things like Map and Set are not supported by all browsers.
2. Judgment of JavaScript type
There are two operators in JavaScript that can be used to determine types. They are typeof and instanceof, but the circle is very small, they don't mix well, and they are notoriously unreliable. It is correct in a few cases, but unreliable in many cases. Just take a look and you’ll know:
// When reliable:
typeof ' sofish' // string
new String('sofish') instanceof String // true
// When unreliable:
typeof [] // object
typeof null // object
'sofish' instanceof String // false
Hmm~ Maybe many beginner JavaScript programmers will curse because of this. Most people already have libraries such as jQuery when they need to use JS. They have encapsulated them so that you can easily detect types. Of course, in fact, it is not troublesome to detect, because the saying "In JavaScript, everything is an object", of course, as mentioned in many documents, undefined is actually just a global property like NaN and Infinity. You probably know that. But "object" can help us:
/* Detection Object type
* @param: obj {JavaScript Object}
* @param: type {String} JS type name starting with uppercase
* @return: {Boolean}
*/
function is(obj, type) {
return Object.prototype.toString.call(obj).slice(8, -1) === type;
}
In this case, we can use the is function to help us determine the type, and this simple function has good compatibility and can be used in your project. For example:
is('sofish', 'String' ) // true
is(null, 'Null') // true
is(new Set(), 'Set') // true
3. JavaScript type conversion
In JavaScript, the type of variables (properties) can be changed. The most common one seen is the conversion between String and Number. How to turn 1 '2' into 12? It is necessary to understand the operator, which is a mathematical operator and a string hyphen in JavaScript. Therefore, novices will often see an interesting phenomenon. When using the sign, sometimes the calculation is not what they want, but using the - sign can always get the "correct" answer.
1 '2' // '12'
1 ( '2') // 3
1 - '2' // -1
This is actually caused by the dual role of . In the above code, you can notice that the second expression uses a number in front of String, forcing its class to be converted to Number. As for the understanding of JavaScript type conversion, in most cases, it is enough to understand that it has dual roles. Other understandable classes can be modified using assignment/overloading, even Error:
var err = new Error();
console .log(err instanceof Error); // true
err = 'sofish';
console.log(err); // 'sofish'
4. JavaScript reference types
This is a difficulty in this article. Compared with basic types, references can add properties and methods to them; a value similar to a reference is a reference, and a value of a reference type is assigned to a variable, and they point to the same value stored in the heap memory. Variables (properties) can be overloaded, but copying can be a very interesting thing, we will talk about it in detail later.
1. Add properties and methods
We will see in the following code that if we assign a basically similar value, it will not report an error, but it will be invalid when getting it:
var arr = [1,2,3];
arr.hello = 'world';
console .log(arr.hello); // 'world'
var str = 'sofish';
str.hello = 'world';
console.log(str.hello); // undefined
2. Operations on reference type values
Since the reference type is stored in the stack memory as a reference, when we point to the same original value, the operation on the value will affect all references; here is an example of reassignment (not the operation of the value) Direct manipulation) will recreate an object without changing the original value. For example:
var arr = [1,2,3] , sofish = arr;
sofish.push('hello world');
console.log(arr); // [1, 2, 3, 'hello world']
// Non-identical type
sofish = ['not a fish']; // When sofish is changed similarly, the original value will not be changed
console.log(arr); // [1, 2 , 3, 'hello world']
3. Copying reference type values
Operations on the original value will affect all references, which is not necessarily what we want. Sometimes we need to copy a brand new object without affecting other references during the operation. In general, there are few specific operations like Date/Function/RegExp..., mainly operations such as adding items and properties to Array and Object. So the main thing we need to understand is how to copy Array and Object objects.
3.1 Copying arrays
In the Array object, there is a slice method that returns an intercepted array. In ES5, filter and so on also return a new array, so we may use this method to copy.
var arr = [1, 2, 3];
var sofish = arr.slice();
// Operating on the new array will not affect the original array
sofish.push('hello world');
console.log(arr); // [1, 2, 3]
3.2 Copy of Objects
We use the slice method to copy Array. In fact, for both Array and Object, we can use the for ... in loop to traverse and assign values to copy.
var obj = { name: 'sofish' }, sofish = {}, p;
for (p in obj) sofish[p] = obj[p];
//Operations on new objects will not affect the original value
sofish.say = function() {};
console.log(obj); // { name: 'sofish' }
3.3 Shadow / Deep Copy
Operations like the above are what we often call shallow copy (Shadow Copy). However, both Array and Object can have multiple layers (dimensions). A copy like this only considers the value of the top layer. Among the possible values, Array and Object still point to the original object. For example:
var arr = [1, { bio: ' not a fish' } ], sofish = [], p;
for(p in arr) {
sofish[p] = arr[p];
}
// Operations on the object `cat` contained in `sofish` will affect the original value
sofish[1].bio = 'hackable';
console.log(arr);// [1 , cat: { bio: 'hackable' } ]
So how to do it? Let’s use a copy() function to solve this problem:
/* Copy object
* @param: obj {JavaScript Object} Original object
* @param: isDeep {Boolean} Whether it is a deep copy
* @return: {JavaScript Object} Return a new object
*/
function copy(obj, isDeep) {
var ret = obj.slice ? [] : {}, p, prop;
// Use with is function
if(!isDeep && is(obj, 'Array')) return obj.slice();
for(p in obj) {
if(!obj.hasOwnProperty(p)) continue;
prop = obj[p];
ret[p] = (is(prop, 'Object') || is(prop, 'Array')) ?
copy(prop, isDeep) : prop;
}
return ret;
}
In this way, we can copy an Array or Object through the copy(obj, isDeep) function. You can test it:
var arr = [1, {bio : 'not a fish'}];
var sofish = copy(arr);
// The shallow copy operation on the first layer does not affect the original value, but affects the second layer
sofish.push('cat');
console.log(arr); // [1, {bio: 'not a fish'}]
sofish[1].bio = 'hello world';
console.log(arr) // [1, {bio: 'hello world'}]
// Deep copy will not affect the original value
sofish = copy(arr, 1);
sofish[1].bio = 'foo or bar';
console.log(arr) ; // [1, {bio: 'hello world'}]
That’s it. You should basically understand all the difficult points about types that you need to understand. Of course, copying is the most troublesome point. In addition to Array and Object that often need to be operated, there is also copying of Date/Function/RegExp.

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

AI Hentai Generator
Generate AI Hentai for free.

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

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).

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
