JavaScript object built-in objects, value types and reference types explained

JavaScript object built-in objects, value types and reference types explained

Object

Objects in JS are a combination of attributes and behaviors , where attributes are static characteristics of objects and behaviors, also known as methods, are dynamic characteristics of objects.

Objects in JavaScript are mainly divided into three categories:

  • Built-in objects

Objects defined in the ES standard can be used in any ES implementation, such as Math String Number Boolean Function Object

  • Host Object

Objects provided by the JS runtime environment, currently mainly objects provided by the browser, such as BOM DOM

  • Custom Objects

Objects created by developers themselves

Object Definition

Define a non-empty object

// Non-null object:
var object name = {
	Property name: value,
	...
	Method name: function([parameters]){
		Method body statements;
	}
	...
}
var p1 = {
	color: 'black', //Add attributes to the object weight: '188g', //Attributes are separated by commas screenSize: 6.5,
	call: function(name){//Add method to the object console.log("Outgoing call: "+name);
	},
	sendMassage: function(msg){
		console.log("The message sent is: "+msg);
	},
	playVideo: function(){
		console.log("play video");
	},
	playMusic: function(){
		console.log("playing music");
	}
}
console.log("Mobile phone color:"+p1['color']); //You can also use object['property'] to output property values ​​console.log("Mobile phone weight:"+p1.weight);
console.log("Screen size:"+p1.screenSize);
p1.call("张三");//Call the object's sending method p1["sendMassage"]("helo");
p1.playVideo();
p1.playMusic();
console.log(p1);

Creating an object using new Object()

var p = new Object(); // Create an empty object p
p2.name = 'Liu Bei';
p2.sex = 'male';
p2.age = 32;
p2.sayHello = function(){
	console.log('Hello');
}
p2.sayHello(); //Call object method

You can use the constructor to create objects:
Syntax: new constructor name ()

function Student(name,sex,age){
	this.name = name; //This refers to the newly created object of the constructor this.sex = sex;
	this.age = age;
	this.show = function(){
		console.log("Name: "+this.name)
		console.log("Sex: "+this.sex)
		console.log("Age: "+this.age)
	}
}
var s1 = new Student('乔峰','男',28);//s1 is a new object created by the constructor, i.e., an instance s1.show();
var s2 = new Student('段煜','男',23);
s2.show();

Note : The constructor may or may not have parameters. If there are no parameters, the parentheses can be omitted.

Iterate over the members of an object

Iterating over the properties and methods of an object: Using the for...in loop

for(var variable name in object name){
	Loop Statement}
function Student(name,sex,age){
	this.name = name;
	this.sex = sex;
	this.age = age;
	this.show = function(){
		console.log("Name: "+this.name)
		console.log("Sex: "+this.sex)
		console.log("Age: "+this.age)
	}
}
// s2 is the object to be traversed var s2 = new Student('段煜','男',23);
for(var k in s2){
	console.log(k);//output name sex age show()
	console.log(s2[k]); // Output Duan Yunan 23 in sequence 
}

in operator <br /> Determines whether a member (attribute) exists in an object. If it exists, it returns true; if it does not exist, it returns false.

JS built-in objects

JavaScript provides many commonly used built-in objects, including the mathematical object Math, the date object Date, the array object Array, and the string object String.

Math Objects

Math object: used to perform mathematical operations on numbers. There is no need to instantiate the object, and its static properties and static methods can be used directly.

Math object: no need to instantiate Math.PI: arithmetic constant PI
Math.abs(x): Returns the absolute value of xMath.max(args...): Returns the maximum numberMath.min(args...): Returns the minimum numberMath.pow(x,y): Returns x raised to the power of yMath.sqrt(x): Returns the square root of xMath.random(): Returns a random number between 0.0 and 1.0Math.round(x): Returns the integer closest to xMath.floor(x): Returns an integer less than or equal to x and closest to itMath.ceil(x): Returns an integer greater than or equal to x and closest to it

Date Object

Date object: You need to use new Date() to instantiate the object before you can use it . Creating an object Date() is a constructor that you can pass parameters to to generate a date object.

insert image description here
insert image description here

// 1. Create a Date object without parameters var date1 = new Date();
console.log(date1);
// 2. Create a Date object with the specified date and time by passing in the year, month, day, hour, minute, and second. // Month is 0-11
var date2 = new Date(2021,4,22,10,17,55);
console.log(date2);
// 3. Pass in a date and time string to create a Date object var date3 = new Date("2021-5-22 18:19:25");
console.log(date3);
console.log(date3.getMonth()) //4
console.log(date3.getTime()) // represents the number of milliseconds between the Date object and midnight on January 1, 1970 console.log(date1.toLocaleDateString()) // 2021/6/14
console.log(date1.toLocaleString()) //2021/6/14 11:17:36 PM
console.log(date1.getFullYear())//2021

Array Object

Array: It is a collection of data of the same type. It is similar to ordinary objects in function and is also used to store some values. Arrays use numbers as indexes to operate internal elements.
Array creation

  • Using Literals
    var arr = [] // Create an empty array
  • Create using new Array
    var arr = new Array(); //define an empty array

There are two ways to determine whether an object is an array:

  • isArray(object name)
  • instanceof: object name instanceof Array
    var arr = [];
    var obj = {};
    console.log(Array.isArray(arr));//true
    console.log(Array.isArray(obj));//false
    console.log(arr instanceof Array);//trrue 

insert image description here

Other array methods have been introduced in detail in previous articles, so I will not explain them here.

String Object

String object: string object, must be created using new String()

Common string methods

- charAt(n) returns the string at position n - concat(s1,s2,...) concatenates multiple strings - charCodeAt(n) returns the ASCII code at position n - split('separator') converts a string into a string array according to the given separator - substr(start,length) extracts length characters from start to form a new string - substring(from,to) extracts the string between from and to to form a new string - toLowerCase() converts uppercase characters in a string to lowercase without affecting the original string and returns a new string - toUpperCase() converts all lowercase characters in a string to uppercase without affecting the original string and returns a new string - replace(str1,str2) replaces str1 in a string with str2 and returns the replacement result without affecting the original string

String object exercises

// Input a string of letters and count the number of times each letter appears in the string var str = 'abBSdXbdea';
var lower = new Array(26);//Store the number of times each of the 26 lowercase letters appears var upper = new Array(26);//Store the number of times each of the 26 uppercase letters appears // Initialize two arrays for(var i=0;i<lower.length;i++){
    lower[i] = 0
    upper[i] = 0
}
for(var k=0;k<str.length;k++){
    if(str.charAt(k)>='a' && str.charAt(k)<='z'){
        lower[str.charCodeAt(k)-97]++
    }else if(str.charAt(k)>='A' && str.charAt(k)<='Z'){
        upper[str.charCodeAt(k)-65]++
    }
}
console.log(lower);
console.log(upper);
/* Input a decimal integer and a number system (2, 8, 16) and convert the decimal integer into the corresponding numerical format and output the remainder method:
               m=15 k=8
               m%k stores the remainder in an array*/
        var m = parseInt(prompt('Please enter an integer:'));
        var k = parseInt(prompt('Please enter a number system (2~16)'));
        var result = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'];
        var arr = new Array(); //Store the result of number system conversion var i = 0;
        while(m!=0){//Convert m to a number system and put the remainder in the arr array arr[i] = m%k;
            m = parseInt(m/k);
            i++;
        }
        var str = '';
        if(k==8){
            str = '0';
        }else if(k==16){
            str = '0x';
        }
        for(var i=arr.length-1;i>=0;i--){
            str += result[arr[i]];
        }
        console.log('The result of the conversion is: '+str);

Value Types and Reference Types

Value type: simple data types (string, numeric, Boolean, undefined, null)
Reference type: complex data type (object) The variable stores the address of the reference

Note: The characteristic of the reference type is that the variable only stores the address of a reference. When assigning a value to a variable, the object is not copied, but the two variables point to the reference of the same object.

The following is an analysis of the stack and heap in memory
Stack : Memory space is automatically allocated and released, and simple data types are stored in the stack.
Heap : Dynamically allocated memory, with variable size and not automatically released. Complex data types are stored in the heap.

insert image description here

It can be seen that for objects stored in the heap memory, the variable actually stores a pointer, which points to another location. This pointer is used to find the properties and values ​​of the objects stored in the heap, and each space is of different size, so specific allocation should be made according to the situation.

This concludes this article about JavaScript objects, built-in objects, value types, and reference types. For more information about JavaScript basic objects, please search for previous articles on 123WORDPRESS.COM or continue browsing the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Detailed explanation of JavaScript's built-in objects Math and strings
  • Detailed explanation of JavaScript's built-in Date object
  • Javascript basics about built-in objects
  • In-depth explanation of the nine built-in objects of JSP
  • JSP built-in objects
  • Introduction to JavaScript built-in objects

<<:  A brief introduction to the usage of decimal type in MySQL

>>:  How to install MySQL 5.7.28 binary mode under CentOS 7.4

Recommend

Two ways to open and close the mysql service

Method 1: Use cmd command First, open our DOS win...

Description of the execution mechanisms of static pages and dynamic pages

1. A static page means that there are only HTML ta...

Detailed explanation of Angular parent-child component communication

Table of contents Overview 1. Overview of input a...

Solve the problem of MySQL using not in to include null values

Notice! ! ! select * from user where uid not in (...

How to allow all hosts to access mysql

1. Change the Host field value of a record in the...

How to change the domestic image source for Docker

Configure the accelerator for the Docker daemon S...

How to switch directories efficiently in Linux

When it comes to switching directories under Linu...

The difference between char, varchar and text field types in MySQL

In MySQL, fields of char, varchar, and text types...

Summary of several common ways to abbreviate javascript code

Table of contents Preface Arrow Functions Master ...

mysql security management details

Table of contents 1. Introduce according to the o...

JavaScript to achieve simple image switching

This article shares the specific code for JavaScr...

How to configure mysql5.6 to support IPV6 connection in Linux environment

Introduction: This article mainly introduces how ...

React concurrent function experience (front-end concurrent mode)

React is an open-source JavaScript library used b...