Re discussion on basic type and reference type of recommendation in Javascript

  • 2021-07-01 06:34:21
  • OfStack

1. Overview of base types and reference types

The values of data types in js include: base type values and reference type values

Basic data type: undefined;; null; boolean; number; string

Reference type value: Saved in memory, js does not allow direct access to memory locations, so it manipulates references instead of actual objects

2. How to Detect Data Types

1. Detection of basic data types: using typeof


var s =  " AAA " ; 
alert(typeof s); // Return string

2. Reference type (object type) detection: Using instanceof


alert(person instanceof Object); 
alert(person instanceof Array); 
alert(person instanceof Regexp);

3. Special case: instanceof always returns true when detecting object, and always returns false when detecting primitive type (because primitive type is not an object)

typeof returns Function when detecting functions and Object when detecting regular expressions

3. Differences between primitive types and reference types

1. You can add attributes to reference types, but not to base types

2. When copying, the basic type is to directly copy a new variable, and there is no relationship between the old and new variables;

The reference type also copies the new variable, but this variable is a pointer, and the new and old pointers point to the same object

3. Function parameter transfer: All parameter transfer principles are to transfer external variables to function parameters by copying. Therefore, the internal operation on parameters of the function has no effect on the external original variables

Let's take parameters as basic types and reference types as examples for verification:


function addTen(num){ 
num += 10; 
return num; 
} 
var count = 20; 
var result = addTen(count); 
// Here, the inside is right num The operation of does not affect the external count Value of  
function setName(obj){ 
obj.name =  " Nicholas " ; 
obj = new Object(); 
obj.name =  " Greg " ; 
} 
var person = new Object(); 
setName(person); 
alert(person.name); // Return to " Nicholas ", indicating that it still does not affect the external person Object's name

Related articles: