Object-oriented programming

Object-oriented programming

1. Built-in objects and functions

1.1 Basic Packaging Type

The classification of data in ES is divided into basic data types (number, Boolean, string, undefined, null, symbol) and reference types (object, function, array)

Strictly speaking, the basic packaging type does not belong to either.

The obvious difference between the basic data type and the reference type is:

Reference types have their own built-in methods, and other methods can be customized to manipulate data, while basic data types cannot

To enable methods to be used on basic data types, ECMAScript provides three special reference types (basic wrapper types): Boolean, Number, String

When reading a value of a base type, a base wrapper type object is created in the background so that methods can be called to manipulate the data samples:

var str = 'test';
//substring(start,end), intercepts strings from start to end, excluding end.
var str2 = str.substring(2);

Q1: Why can't an object call its methods, and how does this work?

The basic packaging types play a role, and the process is implemented internally:
1. When accessing the str property, a special object containing the literal value of the string is created and has a corresponding method, such as substring().
2. The method runs and returns a new string
3. The special object is destroyed, leaving only the original value str.

// How js background handles boxing and unboxing
//Use the String constructor to create an instance that is an object
var str = new String('test'); //Packing
//Objects have built-in methods for developers to call
var str2 = str.substring(2);
//Destroy this instance
str = null;//Unpacking

Q2:When will Js automatically create a corresponding basic wrapper type object

This access process becomes read mode when values of the basic type are retrieved from memory.

var str = 'hhh'
console.log(str) //Read mode, background automatic creation of basic wrapper type objects
var str2 = str   //Assigning to the variable str2 also requires reading the str value, as above

Q3: The main difference between the reference type and the basic packaging type is the lifetime of the object

Reference types: Instances of reference types created using the new operator that are kept in memory until the execution stream leaves the current scope

Basic Packaging Type: Only one line of code is executed instantly and destroyed immediately

var str='lfl';
console.log(str.test);//undefined has been destroyed

Q4: How to add methods or attributes to a base type

  • Prototype method to add corresponding wrapper object
// Through prototype
var str='hello';
// CharAt (index position)
    return this.charAt(this.length-1);
  • Creating String Objects Using the new Operator

    // new String Object by new Operator
    var str2 = new String('test');
    //Valid attributes
    str2.name = 'zhangsan';
    //Effective methods
    str2.age = function () {
      return 66;
    console.log(str); //[String: 'test'] { name: 'zhangsan', age: [Function] }
    console.log(typeof str); //object
    console.log(typeof str.valueOf()); // Override the valueOf() method to return the basic string value represented by the object

    Note: When creating String, Number, and Boolean objects using the new operator, you can add properties and methods to yourself;Or add a prototype method for the corresponding wrapper object;However, we do not recommend this because it will cause a fundamental ambiguity as to whether it is a base type value or a reference type value.

    Boolean type

    There are no specific attributes or methods, generally used directly as a tool method

    // Boolean converts an object as long as it has a value of true  
    // Object is null false
    var falseObj = new Boolean(false);
    var result = falseObj && true;
    // As a tool method

    Number type

    • Built-in properties (static properties, called directly)
    // Maximum
    // minimum value
    NaN Non-numeric value
    NEGATIVE_INFINITY Negative Infinity, returned on overflow
    POSITIVE_INFINITY  Positive infinity, returned when overflowing
    prototype  Enables you to add properties and methods to objects
    • Built-in methods (object methods)
    var num=123;
    // 1.toString converts a number to a string using the specified cardinality
    // 2.toLocaleString converts numbers to strings using local number format order
    console.log(num.toLocaleString()); //123
    // 3.toFixed converts a number to a string with a specified number of digits after the decimal point of the result.
    // 4.valueOf returns the base numeric value of a Number object
    console.log(num.valueOf(),typeof num.valueOf());
    // 5.toExponential converts the object's value to an exponential count.Scientific Counting
    // 6.toPrecision converts the object's value to an exponential count.Scientific Counting

    String type

    • Object Properties
    constructorReference to the function that created the object
    lengthLength of string
    prototypeAllows you to add properties and methods to objects

    String also contains generic methods for objects, such as valueOf(), toLocaleString(), and toString(), which all return the base values of strings.

    • Character method
    var str='Hello World';
    // Returns the character charAt(index) at a specified location 
    // Returns the character encoding charCodeAt(index) for a specified character 
    • String manipulation method
      var str='Hello World';
      // concat(str1,str2...strx)
      console.log(str.concat('Hello','world'));//Hello World
      // Intercept a slice(start,end) of a string
      // Intercepts a string substr(start,length) of a specified length 
      console.log(str.substr(2,6));//llo Wo
    • String Position Method
    var str='Hello World';
    // Retrieval from scratch could not find Return-1  
    //indexOf(str,n) searches for the first STR starting at N and returns the index value of the search
    // Retrieval from the end of the string failed to find Return-1  
    //LastndexOf (str, n) searches for the first STR starting at N and returns the index value of the search
    • Case Conversion Method
    // Uppercase conversion
    console.log(str.toUpperCase());//HELLO WORLD
    // Localization of uppercase conversion
    console.log(str.toLocaleUpperCase());//HELLO WORLD
    // Lowercase conversion
    console.log(str.toLowerCase());//hello World
    // Localization of lowercase conversion
    console.log(str.toLocaleLowerCase());//hello World
    • Pattern matching methods for strings (regular expression matching)
    // Find a match for one or more regular expressions
    //Find information to return matching content, otherwise return null
    console.log(str.match('o'));//[ 'o', index: 4, input: 'Hello World', groups: undefined ]
    // Replace matching regular expressions
    // Return-1 and indexOf were not found to be similar
    console.log(str.replace(/he/i,'hi'));//hillo World
    // Retrieve values that match regular expressions
    // Separator string is an array of strings
    console.log(str.split(' '));//[ 'Hello', 'World' ]

Math Object

Math.min() //Find the minimum value in a set of numbers
Math.max() //Finding the maximum value in a set of numbers
Math.ceil() Round Up
Math.floor() round down
Math.round() Rounding
Math.random() Returns a random number greater than 0 and less than 1 [0,1)


// Built-in Properties
// Π
//square root

// Built-in methods
// Maximum
// minimum value
// Round to integer for decimal values
// ceil() rounding up
// floor() rounding down
// round() rounding
//random() random number
var arr=['Zhu Bajie','Sun WuKong','Tang Monk','Sand Monk']
var result=arr[Math.floor(Math.random())]
console.log(result);//Randomly pick one of the four roles

Date objecthttps://www.w3school.com.cn/jsref/jsref_Obj_Date.asp

constructorReturns a reference to the Date function that created this object.
prototypeEnables you to add properties and methods to objects.
getFullYear()   	Return year such as 2020
getMonth()			Returns the number of months in a date with a return value of 0(1 month)-11(12 month)
getDate()			Return is the number in the date object.
getHours()			Hours in Return Date
getMinutes()		Return minutes from date
getSeconds()		Returns the number of seconds for a date
getDay()			Return Date of the Week
getMilliseconds()	Return milliseconds from date
getTime()			Return a date object in milliseconds

expanded memory bank

Moment.js http://momentjs.cn/

//Use in node.js
//Install moment library using node in current directory
npm install moment --save

//Use in browsers
// You can download js files or use the corresponding cdn file, bootcdn
<script src="moment.js"></script>
// Modular import moment
var moment = require('moment');
// Set the local language to Chinese
// require('moment/locale/zh-cn')
// moment.locale('zh-cn');

console.log(moment().format('MMMM Do YYYY, H:mm:ss a'));//September 2nd 2021, 19:46:24 pm

// Time Stamp Conversion
console.log(moment(parseInt(1630334723399)).format('YYYY-MM-DD HH:mm:ss'));//2021-08-30 22:45:23


Solving the shallow copy problem

// Introducing the lodash function
var _ = require('lodash');
// Solving deep and shallow copies
var obj={
// Using the cloneDeep method
var obj2=_.cloneDeep(obj);
console.log(obj); //{ name: 'zhangsan', age: 19 }
console.log(obj2);//{ name: 'zhangsan', age: 20 }
//1. Split the array into blocks of size length to form a new array_.chunk(array, [size=1])
console.log(_.chunk(['a', 'b', 'c', 'd'], 2));//[ [ 'a', 'b' ], [ 'c', 'd' ] ]
//2. Create a new array that contains all the non-pseudo elements in the original array.compact(array)
// False, null, 0,', undefined, NaN are all false values
console.log(_.compact([0,2,4,true,'zhanngsan',6,NaN,null]));//[ 2, 4, true, 'zhanngsa', 6 ]
//3. Create a slice array and remove the n elements before array by default to 1.Drop (array, [n=1])
// 4. Returns the index value found by the first value in the array array, otherwise returns -1_.IndexOf (array, value, [fromIndex=0]) 
// 5. Create a duplicate array array after de-duplication.Only the first occurrence of an element is preserved_.uniq(array)
console.log(_.uniq([2,2,1,1,4,3,5,3]));//[ 2, 1, 4, 3, 5 ]

Keywords: Javascript

Added by jbingman on Tue, 07 Sep 2021 19:46:25 +0300