Analysis on basic types and reference types of JavaScript

Source: Internet
Author: User
This article mainly introduces the basic types of JavaScript and the detailed description of the reference types, and explains such content as type judgment, type conversion, and type replication. If you need it, you can refer to the following section for JavaScript types, it can be simply summarized as: Compared with a strong type language, it is a weak (loose) type language; there are basic types and reference types, the difference is that a fixed space exists in the stack memory, a non-fixed space is saved in the heap memory, and a pointer pointing to the implementation position is saved in the stack memory.

There are a lot of books on the market. This article will talk about several aspects, which may require you to have a simple understanding of JavaScript, especially the JavaScript type. If you still have different solutions, you can pick up a book about JavaScript and flip it over.

I. Basic Types and reference types

1. Basic Type: Undefined/Null/Boolean/Number/String
2. Reference Type: Object/Array/Function/Date/RegExp/Error/Map/Set...

Why isn't the reference type fully enumerated, because it's enough for you to know so much about it, at least in the article I'm talking about. Others may be rarely used, and not all browsers such as Map and Set support them.

Ii. JavaScript type judgment

There are two operators in JavaScript that can be used to determine the type. They are typeof and instanceof, but the circle is small, they are not so good, it is out of the name is not reliable. In a few cases, it is also true. In many cases, it is unreliable. Let's see:

The Code is as follows:


// When reliable:
Typeof 'sofish '// string
New String ('sofish ') instanceof String // true

// Unreliable:
Typeof [] // object
Typeof null // object
'Sofish 'instanceof String // false


Er ~ Many new JavaScript programmers may exploit this vulnerability. Most people already have libraries such as jQuery when they need to use JavaScript, and they have encapsulated them so that you can easily detect types. Of course, in fact, it is not difficult to detect, because the sentence "in JavaScript, everything is an object", of course, as mentioned in many documents, undefined actually matches NaN, infinity is only a global attribute. You probably know. But "object" can help us:

The Code is as follows:


/* Check object type
* @ Param: obj {JavaScript Object}
* @ Param: type {String} Name of the JS type starting with an uppercase letter
* @ Return: {Boolean}
*/
Function is (obj, type ){
Return Object. prototype. toString. call (obj). slice (8,-1) === type;
}

In this way, 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. Example:

The Code is as follows:


Is ('sofish ', 'string') // true
Is (null, 'null') // true
Is (new Set (), 'set') // true

Iii. JavaScript type conversion

In JavaScript, the type of a variable (attribute) can be changed. Most often seen is the conversion between String and Number. How can we change 1 + '2' to 12? The operator + is a mathematical operator and a String concatenation character in JavaScript. Therefore, new users often see an interesting phenomenon. When using the plus sign, sometimes the calculated result is not desired, but the "correct" answer is always obtained by using the minus sign.

The Code is as follows:


1 + '2' // '12'
1 + (+ '2') // 3
1-'2' //-1


This is actually caused by the dual role of +. In the code above, we can note that the second expression uses a + sign before the String to forcibly convert its class to Number. In most cases, understanding + has a dual role. Other understandable classes can be modified using value assignment/overload, and even include Error:

The Code is as follows:


Var err = new Error ();
Console. log (err instanceof Error); // true

Err = 'sofish ';
Console. log (err); // 'sofish'



Iv. JavaScript reference type

This is a difficult point in this article. Similar to the basic type, you can add attributes and methods to a reference. A reference similar value is a reference, and a value of the reference type is assigned to a variable, they point to the same value stored in heap memory. Variables (attributes) can be reloaded, but copying is an interesting thing. We will discuss it in detail later.

1. Add attributes and Methods

The following code will show that, if we assign a value similar to a basic one, it will not report an error, but it will fail to be obtained:

The Code is as follows:


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. Operation of reference type value

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, re-assignment (not a direct operation on the Value) will re-create an object and will not change the original value. For example:

The Code is as follows:


Var arr = [1, 2, 3], sofish = arr;
Sofish. push ('Hello World ');
Console. log (arr); // [1, 2, 3, 'Hello world']

// Not of the same type
Sofish = ['not a fish ']; // The original value is not changed when sofish is similar to a change.
Console. log (arr); // [1, 2, 3, 'Hello world']

3. Copy the reference type value

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 operations. In general, like Date/Function/RegExp... There are few specific operations, such as adding items and attributes to arrays and objects. Therefore, we need to understand how to copy Array and Object objects.


3.1 copying an array

In the Array object, the slice method returns a truncated Array, and filter in ES5 also returns a new Array, so we may use this method for copying.

The Code is as follows:


Var arr = [1, 2, 3];
Var sofish = arr. slice ();

// Operations on the new array will not affect the original array.
Sofish. push ('Hello World ');
Console. log (arr); // [1, 2, 3]


3.2 copying objects

In Array replication, we use the slice method. in fact, we can use the for... in loop for Array and Object traversal and assign values for copying.

The Code is as follows:


Var obj = {name: 'sofish '}, sofish = {}, p;
For (p in obj) sofish [p] = obj [p];

// The operation on the new object does not affect the original value.
Sofish. say = function (){};
Console. log (obj); // {name: 'sofish '}

3.3 Shadow/Deep Copy

The operation above is what we often call Shadow Copy ). However, both Array and Object can have multiple layers (dimensions). Copying like this only takes into account the values at the top layer, the Array and Object in the possible values still point to the original Object. For example:

The Code is as follows:


Var arr = [1, {bio: 'Not a fish '}], sofish = [], p;
For (p in arr ){
Sofish [p] = arr [p];
}

// The operation on the 'cat' object contained in 'sofish 'will affect the original value.
Sofish [1]. bio = 'hackable ';
Console. log (arr); // [1, cat: {bio: 'hackable'}]


So how to do it? Use a copy () function to solve this problem:

The Code is as follows:


/* Copy the object
* @ Param: obj {JavaScript Object} original Object
* @ Param: whether isDeep {Boolean} is a deep copy
* @ Return: {JavaScript Object} returns a new Object.
*/
Function copy (obj, isDeep ){
Var ret = obj. slice? []: {}, P, prop;
// Used with the 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 use the copy (obj, isDeep) function to copy an Array or Object. You can test it:

The Code is as follows:


Var arr = [1, {bio: 'Not a fish '}];
Var sofish = copy (arr );

// The operation of the first layer does not affect the original value but the operation of 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'}]

// The original value is not affected by the deep copy operation.
Sofish = copy (arr, 1 );
Sofish [1]. bio = 'foo or bar ';
Console. log (arr); // [1, {bio: 'Hello world'}]

So far. You should have a basic understanding of the difficult types. Of course, replication is the most troublesome point. In addition to arrays and objects that require frequent operations, there is also replication of Date/Function/RegExp.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.