Elementary analysis of JavaScript basic type and reference type _ basic knowledge

Source: Internet
Author: User
Tags new set shallow copy

For JavaScript types, it is simple to generalize that it is a weakly (loosely) typed language relative to a strongly typed language; There are basic types and reference types, and they are the difference between a fixed space that exists in stack memory, A no fixed space is saved in the heap memory and a pointer to the implementation location is saved in the stack memory.

There are many books on the market that are not small. This article will talk about several aspects that may require you to have some simple knowledge of JavaScript, especially the type of JavaScript. If you have a different solution, you can pick up a book about JavaScript, and then look at this article.

One, basic type and reference type

1. Basic type: undefined/null/boolean/number/string
2. Reference type: Object/array/function/date/regexp/error/map/set ...

Why is the reference type not enumerated, because it's enough for you to know so much, at least in this one I'm talking about. Others may be used infrequently, and not even all browsers like MAP or Set are supported.

Second, the JavaScript type of judgment

There are two operator in JavaScript that can be used to determine the type. They are typeof and instanceof, but the circle is very small, they do not mix so well, is out of the name of the unreliable. A few things are right, and in many cases they are not. Look at it and know:

Copy Code code as follows:

The time to be reliable:
typeof ' Sofish '//String
New string (' Sofish ') instanceof string/True

When it's not reliable:
typeof []//Object
typeof Null//Object
' Sofish ' instanceof String//False


Well, maybe a lot of beginner JavaScript programmers will swear it. Also most people need to use JS when they have a library such as jQuery, they have done encapsulation, so that you can easily detect types. Of course, the test is not trouble, because the sentence "in JavaScript, everything is an object", of course, as many documents said, undefined in fact and NaN, Infinity are just a global attribute. You probably know it. But "objects" can help us:

Copy Code code as follows:

/* Detect Object Type
* @param: obj {JavaScript Object}
* @param: type {String} with a JS name beginning in uppercase
* @return: {Boolean}
*/
function is (obj, type) {
return Object.prototype.toString.call (obj). Slice (8,-1) = = type;
}

In this way, we can use is this function to help us to fix the type judgment, and this simple function has the very good compatibility, may use in your project. The situation is as follows:

Copy Code code as follows:

Is (' sofish ', ' String ')//True
Is (null, ' null ')//True
Is (new Set (), ' Set ')//True

Iii. Conversion of JavaScript types

In JavaScript, the type of a variable (property) can be changed. The most commonly seen is the conversion between String and number. How to Turn 1 + ' 2 ' into 12? It is necessary to understand the + number operator, which is a mathematical operator and also a string hyphen in JavaScript. So the novice will often see an interesting phenomenon, when the use of the + number is sometimes calculated not to want, and with the number but always get the "correct" answer.

Copy Code code as follows:

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

This is actually because of the dual role of the + caused. In the preceding code, you notice that the second expression uses a + number before the String, forcing its class to be converted to numbers. For JavaScript, the type conversion understanding, in most cases, as long as the Understanding + has a dual role can be. Other understandable classes, similar to those that can be modified with assignment/overload, even include Error:

Copy Code code as follows:

var err = new Error ();
Console.log (Err instanceof Error); True

Err = ' sofish ';
Console.log (ERR); ' Sofish '



Four, JavaScript reference type

This is a difficult point in this paper. A reference can add properties and methods to a base type, a reference to a value similar to a reference, assigning a value of a reference type to a variable, and they point to the same value stored in the heap memory. Variables (properties) can be overloaded, but copying can be an interesting thing, and we'll be more specific later.

1. Add properties and methods

As we'll see in the following code, assuming we have an essentially similar assignment, it does not give an error, but is invalidated when it is acquired:

Copy Code code 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. Reference to the operation of the type value

Because reference types are stored in stack memory as a reference, then when we point to the same original value, the operation on the value will affect all references; Here's an example where a re-assignment (not a direct operation on a value) will re-create an object without altering the original value. Like what:

Copy Code code as follows:

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

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

3. Replication of reference type values

Operations on raw values affect all references, which are not necessarily what we want, and sometimes we need to replicate an entirely new object that does not affect other references. And the general situation also, like date/function/regexp ... Rarely have specific operations, mainly like Array and Object will have add items, attributes, and so on. So the main thing we need to understand is how to copy Array and object objects.


3.1 Replication of arrays

In the array object, there is a slice method that returns an intercepted array, and the filter in ES5 also returns a new array, so we might use this method to replicate.

Copy Code code as follows:

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

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


3.2 Replication of objects

In the replication of array we use the slice method, in fact, for the array and Object, you can use the for ... in loop to iterate and assign values to replicate.

Copy Code code as follows:

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

Operations on new objects do not affect original values
Sofish.say = function () {};
Console.log (obj); {name: ' Sofish '}

3.3 Shadow/deep Copy

Like the above operation, we often say that the shallow copy (Shadow copy). However, the array and object can have multiple layers (dimensions), such as a copy only take into account the topmost layer of the value, in the possible value of the array and object are still pointed to the original object. Like what:

Copy Code code as follows:

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

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


So how do you do that? Here's a copy () function to solve this problem:
Copy Code code as follows:

/* Copy Object
* @param: obj {JavaScript object} original objects
* @param: isdeep {Boolean} is a deep copy
* @return: {JavaScript Object} returns a new object
*/
function copy (obj, isdeep) {
var ret = Obj.slice? []: {}, P, prop;
Use 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 copy an Array or Object through the copy (obj, isdeep) function. Can test:
Copy Code code as follows:

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

Shallow copy does not affect the original value for the first level of operation, 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 '}]

A deep copy does not affect the original value
Sofish = Copy (arr, 1);
Sofish[1].bio = ' foo or bar ';
Console.log (arr); [1, {bio: ' Hello World '}]

To this. You basically have to understand the difficult point about the type, should be basic understanding. Of course, replication is one of the most troublesome points, with the exception of Array and Object, which are often required to operate, as well as DATE/FUNCTION/REGEXP replication.

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.