JavaScript object-oriented Foundation

Keywords: Javascript

If you want to see the content of basic grammar, please move on JavaScript basic syntax

1, Custom object

01. Concept of object

  • In JavaScript, an object is an unordered collection of related properties and methods
  • All things are objects, such as strings, values, arrays, functions, etc
  • Objects are composed of properties and methods
    • Attribute: the characteristic of a thing, which is represented by an attribute in an object (a common noun)
    • Method: the behavior of things is often expressed in the object (common verb)

02. Create object

(1) Use object literals

var obj = {};

var star = {
    name: 'pink',
    age: 18,
    sex: 'male',
    
    sayHi: function () {
        alert('Hello, everyone');
    }
}; 

03. Operation object

(1) Add object properties and methods

  • Direct name, property name, method name, and then assign values to them
obj.aa = 10;
obj.bb = 20;
obj.sayHi = function() {
	alert('hello everyone');
}

(2) Modify object properties and methods

  • Direct name, property name, method name, and then give them a new name
obj.aa = 30;
obj.bb = 40;
obj.sayHi = function() {
    alert('Ah, ah');
}

(3) Use properties and methods

// attribute
console.log(obj.aa);
console.log(obj['bb']);

// method
obj.SayHi();
obj['sayHi']();

(4) Traverse the properties and methods of the object

  • The for... in statement is used to traverse objects and arrays
var obj = {
    a: 1,
    b: 2,
    c: 3
}

for (var k in obj) {
    console.log(k + " " + obj[k]);      // Here K is the attribute name and method name, obj[k] is the attribute value and method body
}

(6) One thing to pay special attention to

  • If an object does not have an attribute and we use it, the value of the attribute is undefined and the corresponding Boolean value is false

04. Create object by custom constructor

  • Similar to classes in Java
  • Constructor is a special function, which is mainly used to initialize objects
  • matters needing attention
    • The first letter of the Convention constructor is capitalized, such as: function Stars() {}
    • You need to add this before the properties and methods to represent the properties and methods of the current object
    • Use new to call the constructor. The function of the new keyword is as follows
      • Create an empty object before the constructor code executes
      • Modify the point of this and point this to the created empty object
      • Execute the code in the constructor to add properties and methods to the new object
      • After the function is executed, it automatically returns the created new object (so the return statement is not required in the constructor)
// Declaration constructor
function Constructor name(Parameter 1, parameter 2, parameter 3...) {
    this.Property name 1 = Parameter 1;
    this.Property name 2 = Parameter 2;
    this.Property name 3 = Parameter 3;
    this.Method name = Function body;
}

// Call the constructor to create the object
var obj = new Constructor name(Argument 1, argument 2, argument 3);

05. Design mode - factory mode, using factory functions to create objects

function createPerson(name, age, job) {
    var person = new Object();
    person.name = name;
    person.age = age;
    person.job = job;
    person.sayHi = function() {
        console.log('Hello,everyBody');
    }
    return person;
}

var p1 = createPerson('Zhang San', 22, 'actor');
var p2 = createPerson('Zhang San', 28, 'runner');

2, Math object

01. Common attributes and methods

Property, method namefunction
Math.PIPI
Math.floor()Round down
Math.ceil()Round up
Math.round()Round to the nearest. Note - 3.5. The result is - 3
Math.abs()absolute value
Math.max()Find the minimum value
Math.min()Find the maximum value
Math.random()Gets a random value in the range [0,1]

02. Simple application: obtain random integers in the specified range

function getRandom(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

for (var i = 0; i < 10; i++) {
    console.log(getRandom(5, 10));
}

3, Date object

01. Instantiate object

(1) Returns the date object corresponding to the current time

var now = new Date(); 

(2) Returns a date object at a specified time

  • Common writing method of time parameter: "yyyy MM DD HH: mm: SS"
var future = new Date('2020/10/1'); 
var date1 = new Date(2019,10,1);

02. Date formatting

var date = new Date();    

console.log(date.getFullYear());    // year
console.log(date.getMonth() + 1);   // Month. The returned month is 1 month smaller. Remember to add 1 month to the month
console.log(date.getDate());        // day
console.log(date.getDay);           // Week, Monday returns 1, Saturday returns 6, and Sunday returns 0
console.log(date.getHours());       // Time
console.log(date.getMinutes());     // branch
console.log(date.getSeconds());     // second

03. Get timestamp

  • Based on milliseconds since January 1, 1970
// 1. Call method: valueOf()
var now = new Date();
console.log(now.valueOf())

// 2. Call method: getTime()
var now = new Date();
console.log(now.getTime())

// 3. 
var now = + new Date();

// 4. The method provided in HTML5 has compatibility problems
var now = Date.now();

04. Application

(1) Encapsulates a function that returns the current date and time

  • Format YY MM DD HH: mm: SSS
function getTimer() {
    var time = new Date();
    var year = time.getFullYear();
    var month = time.getMonth() < 10 ? "0" + time.getMonth() : time.getMonth();
    var date = time.getDate() < 10 ? "0" + time.getDate() : time.getDate();
    var hour = time.getHours() < 10 ? "0" + time.getHours() : time.getHours();
    var minute = time.getMinutes() < 10 ? "0" + time.getMinutes() : time.getMinutes();
    var second = time.getSeconds() < 10 ? "0" + time.getSeconds() : time.getSeconds();
    return year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second;
}

console.log(getTimer());

(2) Countdown case

function countDown(time) {
    var nowTime = new Date().getTime(); // Returns the timestamp of the current time
    var inputTime = time.getTime(); // Returns the total timestamp of the user input time
    var times = (inputTime - nowTime) / 1000; // Total seconds remaining
    var date = parseInt(times / 60 / 60 / 24); // day
    date = (date < 10) ? "0" + date : date;
    var hour = parseInt((times / 60 / 60) % 24); //Time 
    hour = (hour < 10) ? "0" + hour : hour;
    var minute = parseInt((times / 60) % 60); // branch 
    minute = (minute < 10) ? "0" + minute : minute;
    var second = parseInt(times % 60); // second 
    second = second < 10 ? "0" + second : second;
    
    return date + "day" + hour + "Time" + minute + "branch" + second + "second";
}

// Date object passed in as of time
console.log(countDown(new Date("2021-10-1 00:00:00")));

4, Array object

01. Two ways to create arrays

(1) Literal mode

var Array variable name = [Array variable name];

(2) Instantiate array objects

var Array variable name = new Array(Array variable name);

Note: you can pass in parameters when creating an array
	If only one number is passed in as a parameter, the parameter specifies the length of the array
	If multiple parameters are passed in            These parameters are treated as elements of the array

02. Check whether it is an array

(1) instanceof keyword

  • Determine whether an object is an instance of a constructor
var arr = [1, 23];
var obj = {};

console.log(arr instanceof Array);  // true
console.log(obj instanceof Array);  // false
console.log(obj instanceof Object); // true

(2) Array.isArray()

  • Used to determine whether an object is an array object
  • isArray() is a method provided in HTML5 and has compatibility problems
var arr = [1, 23];
var obj = {};

console.log(Array.isArray(arr));   // true
console.log(Array.isArray(obj));   // false

(3) typeof keyword

  • View the data type of the variable
    • Simple data types: Number, String, Boolean, Undefined, Null
    • Complex data type: object
var arr = [1, 23];
var obj = {};
var num = 56;
var str = "abcd";

console.log(typeof arr); // object
console.log(typeof obj); // object
console.log(typeof num); // number
console.log(typeof str); // string

03. Common methods of adding and deleting array elements

var arr = ["a", "b", "c", "d"];

// 1. unshift() adds one or more elements to the beginning and returns the modified length of the array
arr.unshift("aa");
arr.unshift(0, 1, 2);

// 2. push() adds one or more elements to the end and returns the modified length of the array
arr.push("aa");
arr.push(0, 1, 2);

// 3. shift() deletes the first element and returns it
arr.shift();

// 4. pop() deletes the last element and returns it
arr.pop();

04. Method of changing array arrangement order

(1) Two methods

Method nameexplainModify original arrayReturn value
reverse()Flip array, no parametersChange original arrayReturns the changed new array
sort()Array sorting, with parametersChange original arrayReturns the changed new array

(2) Detailed explanation of sort() method

Step by step sort() method in JavaScript

05. Find the index of the corresponding element

(1) indexOf()

  • Find the index of the corresponding element from front to back. If it cannot be found, return - 1

(2) lastIndexOf()

  • Find the index of the corresponding element from the back to the front. If it is not found, return - 1

(3) Use demo

var arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 2];
            
console.log(arr.indexOf(2)); // 2
console.log(arr.lastIndexOf(2)); // 9
console.log(arr.lastIndexOf(2)); // -1

06. Convert array to string

(1) toString()

  • Split each item with ','
var arr = [1, 2, 3, 4];

var str = arr.toString();

console.log(str); // "1,2,3,4"

(2) join()

  • Converts the array to a string according to the specified characters
  • If the join method does not pass in parameters, the elements are spliced according to ","
var arr = [1, 2, 3, 4];
var str = arr.join("+");
console.log(str); // "1+2+3+4"

var arr = [1, 2, 3, 4];
var str = arr.join("--");
console.log(str); // "1--2--3--4"   

07. Merge arrays

  • concat(): connect the elements of the parameter array to the back of the specified array, change the original array, and return the changed array
var arr1 = [1, 2, 3, 4], arr2 = [5, 6, 7, 8];

arr3 = arr1.concat(arr2);
console.log(arr3); // [1,2,3,4,5,6,7,8]



var num1 = [1, 2, 3], num2 = [4, 5, 6], num3 = [7, 8, 9];

var num4 = num1.concat(num2, num3);
console.log(num4); // [1, 2, 3, 4, 5, 6, 7, 8, 9]

08. for... in traversal array

var arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 2];

for (var k in arr) {
    console.log(k); // In this case, k corresponds to the index
    console.log(arr[k]); // Elements corresponding to index k
}

5, Basic package type

  • To facilitate the operation of basic data types, JavaScript provides three special reference types: String, Number and Boolean
  • In fact, whenever a basic type value is read, an object of the corresponding basic wrapper type will be created in the background, so that some methods can be called to manipulate the data
  • These are the basic wrapper types, which wrap simple data types into complex data types, so that the basic data types have properties and methods

What's wrong with the following code

var str = 'andy';
console.log(str.length); // 4
  • Logically, basic data types have no properties and methods, while objects have properties and methods, but the above code can be executed
  • This is because js wraps basic data types into complex data types

The implementation process is as follows:

// 1. Generate temporary variables and wrap simple types into complex data types
var temp = new String('andy');

// 2. Assign a value to the character variable we declare
str = temp;

// 3. Destroy temporary variables
temp = null;

6, String object

01. Immutability of string

  • It means that the value of the string is immutable, but the address can be changed. When the address is changed, a new memory space will be opened in memory.
  • Due to the immutability of strings, there will be efficiency problems when "splicing a large number of strings"

02. Convert string to numeric

(1) parseInt(String)

var s = "123";

var num = parseInt(s);

console.log(typeof num); // number

(2) parseFloat(String)

var s = "123.456";

var num = parseFloat(s);

console.log(typeof num); // number

(3) Number(String)

var s1 = "123";
var s2 = "123.456";

var num1 = Number(s1);
var num2 = Number(s2);

console.log(typeof num1); // number
console.log(typeof num2); // number

(4) Implicit conversion

  • For (subtract, multiply, divide) only
console.log("40" + 5); // "405"
console.log("40" - 5); // 35
console.log("40" * 5); // 200
console.log("40" / 5); // 8

03. Common methods of string

(1) indexOf() method

  • Finds the index of the specified character, starting from 0
  • Look from front to back
var str = "abcdabcd";

// 1. Search from the first index
console.log(str.indexOf("a")); // 0
console.log(str.indexOf("e")); // -1, not found return - 1

// 2. Search from the specified index
console.log(str.indexOf("a", 0));  // 0
console.log(str.indexOf("a", 1));  // 4

(2) lastIndexOf() method

  • Find it from back to front. The method is similar to indexOf()

(3) Find the corresponding character according to the index

var str = 'andy';

// 1. charAt(index) returns the corresponding characters according to the index
console.log(str.charAt(3)); // 'y'

// 2. str[index] H5 [new]
console.log(str[0]); // a

// 3. charCodeAt() returns the ASCII value of the character according to the index [Purpose: judge which key the user pressed]
console.log(str.charCodeAt(0)); // 97

(4) Traversal string

var str = "abcdefg";

for (var i = 0; i < str.length; i++) {
    console.log(str[i]);
}

for (var k in str) {
    console.log(str[k]);
}

(5) replace()

  • Replaces some characters (strings) with others and returns a new string, replacing only the first character (string) that appears
var str = "andyandy";
var strs = str.replace("and", "b");
console.log(strs); // byandy

(6) concat() method

  • Splices strings, does not change the original string, and returns a new string
var str = "andy";
var newStr1 = str.concat("red");
var newStr2 = newStr1.concat(1, null, 3);

console.log(newStr1);    // "andyred"
console.log(newStr2);    // "andyred1null3"
console.log(str);        // "andy" does not change the original string

(7) split() method

  • Splits a string into arrays and returns a new array
var str1 = "red, pink, blue";
var arr1 = str1.split(",");
console.log(arr1); // [red,pink,blue]

var str2 = "red&pink&blue";
var arr2 = str2.split("&");
console.log(arr2); // [red,pink,blue]

(8) substr(startIndex, len) method

  • Intercepts the string and returns the intercepted part
var str1 = 'The spring breeze of reform is blowing all over the ground';
var newStr1 = str1.substr(2, 3);
console.log(newStr1); // "Spring breeze"

var str2 = '0123456789';
var newStr2 = str2.substr(4, 4);
console.log(newStr2); // "4567"

7, Simple and complex data types

01. Simple type (basic data type, value type)

  • During storage, the value itself is stored in the variable, including string, number, boolean, undefined and null

02. Complex data type (reference type)

  • During storage, the address is stored in the variable. Objects (system objects, user-defined objects) created through the new keyword, such as Object, Array, Date, etc

03. Heap and stack

(1) Stack (operating system)

  • Store simple data types

(2) Heap (operating system)

  • Storing complex types (objects) is generally allocated and released by programmers. If programmers do not release them, they are collected by garbage collection mechanism

04. Data storage method

(1) Storage of simple data types

  • The data of value type variables is stored directly in variables (stack space)

(2) Storage of complex data types

  • Reference type variables store addresses in stack space, and real object instances are stored in heap space

05. Transfer parameters of different data types

(1) Simple data type parameters

  • The formal parameter of a function can also be regarded as a variable
  • When we pass a value type variable as a parameter to the formal parameter of a function, we actually copy the value of the variable in the stack space to the formal parameter. Any modification to the formal parameter inside the method will not affect the variables outside the method

(2) Complex data type parameters

  • The formal parameter of a function can also be regarded as a variable
  • When we pass a reference type variable to a formal parameter, we actually copy the heap address saved by the variable in the stack space to the formal parameter. The formal parameter and the actual parameter actually save the same heap address, so we operate on the same object, which will affect variables outside the method

Posted by lanbor on Mon, 20 Sep 2021 19:08:12 -0700