Home > Web Front-end > JS Tutorial > body text

A brief analysis of JavaScript basic types and reference types_Basic knowledge

WBOY
Release: 2016-05-16 16:46:39
Original
1180 people have browsed it

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:

Copy code The code is as follows:

// 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:

Copy code The code is as follows:

/* 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:

Copy code The code is as follows:

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.

Copy code 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 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:

Copy code The code is as follows:

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:

Copy code 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. 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:

Copy code The code is as follows:

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.

Copy code The code is as follows:

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.

Copy code The code is as follows:

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:

Copy code The code is as follows:

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 code The code is as follows:

/* 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:
Copy code The code is as follows:

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.

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template