JS advanced object-oriented chapter (including this judgment rule, deep / shallow copy, prototype / prototype chain, etc.)

1, Cognition object

1. What is it

  • An object is a collection of key value pairs (k:v), which represents the mapping relationship between attributes and values
  • The order should be considered in the array. The object does not consider the order, but depends on the mapping relationship

2. Object syntax

  • k and v are separated by colons, each group of k:v is separated by commas, and the last k:v pair can be followed without commas
 const obj = {
            name: 'dudu',
            age:18,
            sex:'female'
        }
  • If the key name of an attribute does not conform to the js representation naming convention, the key name must be enclosed in quotation marks
 const obj = {
            'test-key':'test'
        }

3. Access properties

  • Accessed through point syntax, similar to subscripts in an array
obj.name // 'dudu'
obj.age // 18
  • For those that do not conform to the js naming convention, they must be accessed using the writing method of square brackets [], and single quotation marks should be added inside the square brackets
obj['test-key'] // test
  • If the attribute name is stored as a variable, it must be accessed in square brackets. At this time, the square brackets are not quoted inside
 const obj = {
            name: 'dudu',
            age:18,
            sex:'female',
            'test-key':'test'
        }
        var key = 'name'

        obj.key // undefined
        obj[key] // dudu

4. Change properties

  • Directly use the assignment operator = reassign
obj.age = 20

5. Create attributes

  • If the object itself does not have an attribute, this attribute will be automatically created when using point syntax assignment
obj.tset = 'establish'

6. delete attribute

  • Delete an attribute of an object through the delete operator
delete obj.test

2, Object method and object traversal

  • If a property value is a function, it is also called a method of an object
  • The method of the object is also called through point syntax
const obj = {
            name:'dudu',
            sayHello() {
                console.log("hello")
            }
        }
        obj.sayHello() // hello
  • Object needs to pass for in... Loop traversal key
for(let k in obj) {
            console.log('attribute'+k+'The value of is'+obj[k])
        }

3, Deep and shallow cloning of objects

1. Basic type and reference type



        var a = 3
        var b = a
        a++
        console.log(a) // 4
        console.log(b) //3

        var arr1 = [1,2,3,4]
        var arr2 = arr1
        arr1.push(5)
        console.log(arr1) // [1,2,3,4,5]
        console.log(arr2) // [1,2,3,4,5]
  • Basic types: number, string, Boolean, undefined, null
  • Reference types: object, array, function, regexp, etc

2. The object is a reference type

  • You cannot clone an object with the syntax of var obj2 = obj2
  • When using = = or = = = to compare objects, they compare whether they point to the same object in memory, not whether the values are the same
var obj1 = {
        a:1,
        b:2,
        c:3
    }
    var obj2 = {
        a:1,
        b:2,
        c:3
    }
    // obj1 and obj2 are two different objects
    console.log( obj1 == obj2) //false
    console.log(obj1 === obj2) //false

3. Shallow cloning of objects

  • Only the "surface layer" of the object is cloned. If some attribute values of the object are reference types, they are not cloned, but their references are passed
var obj1 = {
        a:1,
        b:2,
        c:[12,23,34]
    }
    var obj2 = obj1; //Cloning cannot be realized. obj1 and obj2 point to the same stack and belong to the same object
    
    /**Shallow cloning*/
    var obj3 = {}
    for(var k in obj1) {
        // Every time you traverse a K attribute, add a K attribute with the same name to obj3, and the value is the same as that of obj1
        // a. b is a basic type and will be cloned during assignment, so a and b in the two objects are not related to each other
        // c is a reference type. It will not be cloned during assignment, but let c in two objects point to the same stack
        obj3[k] = obj1[k]
    }

4. Deep cloning of objects

  • Clone the whole picture of an object, whether it is a basic type or a reference type
  • Deep cloning of objects also uses recursion
function deepClone(obj) {
        // Both arrays and objects are reference types, but their traversal methods are different. Arrays are traversed through for and objects are traversed through for In traversal
        // typeof cannot judge the object and array. Both will return object
        // Array.isArray() can judge whether an object is an array, so you can judge whether it is an array first, not an array, and then whether it is an object
        if(Array.isArray(obj)) {
            var result = []
            // Walk through each item in the array and add it to the new array
            for(var i=0;i<obj.length;i++) {
                // Before adding, you also need to call the function to judge the type (recursion)
                result.push(deepClone(obj[i]))
            }
        }else if(typeof obj == 'object') {
            var result = {}
            // Traverse the object and add it to the new object
            for(var k in obj) {
                // Before adding, you also need to call the function to judge the type (recursion)
                result[k] = deepClone(obj[k])
            }
        }else {
            // Basic type, which can be assigned directly
            var result = obj
        }
        // Finally, return the final result
        return result
   }

   var obj1 = [22,33,{
       name:'dudu',
       age:18,
       hobbies:['run']
   }]
   var obj2 = deepClone(obj1)

5. Recursion

5.1 what is it

  • The function itself can be called inside the function to initiate the iteration of the function, that is, the function itself calls itself

5.2 recursive elements

  • Boundary condition: determines when recursion terminates, also known as recursion exit
  • Recursive mode: how big problems are decomposed into small problems, also known as recursive body
 /** recursion
     *  Class of 4
     **/
    // Seeking stratum
    function factorial(n) {
        // Recursive exit: if n is 1, return 1 directly
        if(n == 1) return 1
        // Otherwise, continue to take the factorial of n-1
        return n * factorial(n-1)
    }
    var res = factorial(4)
    console.log(res) //24

5.3 Fibonacci series

  • For example: 1, 1, 2, 3, 5, 8, 13 and 21
// Returns the value corresponding to the item with subscript n in the Fibonacci sequence
    function sequence(n) {
        if(n == 0 || n ==1 ) return 1
        return sequence(n-1) + sequence(n-2)
    }
    console.log(sequence(7)) // 21

4, Context of function this

  • this keyword represents the context object of the function
  • The specific meaning of this should be judged by the "preface and postscript" when calling the function

1. The context of the function this is determined by the calling method of the function

  • Called as a function, this points to window
  • It is called in the form of object management, and this points to the called object
var person = {
    name:'dudu',
    age:18,
    sayHello() {
        console.log(`I am ${this.name},this year ${this.age}Years old`)
    }
   }
   person.sayHello() // this points to the person object
   var sayHello = person.sayHello 
   sayHello() // this points to window
  • The context can be determined only when the function is called

2. Context rules

  1. Rule 1: when an object calls a function (object. Method), the context is the object of management
var obj1 = {
       a:1,
       b:2,
       fn() {
           console.log(this.a+this.b)
       }
   }
   var obj2 = {
       a:3,
       b:4,
       fn:obj1.fn
   }
   obj2.fn() // Obj2 calls, so this is obj2. Then, the function is also a reference type. When assigning values, it will point to the same heap, so 7 will be printed
function outer() {
       var a = 20
       var b = 12
       return {
           a:33,
           b:44,
           fn() {
               console.log(this.a+this.b)
           }
       }
   }
   outer().fn() // outer() returns an object, so it finally forms an object Method, this will point to the returned object, so 77 will be printed
  1. Rule 2: if the parentheses directly call the function (function ()), the upper and lower ten thousand are window objects
var obj1 = {
       a:1,
       b:2,
       fn() {
           console.log(this.a+this.b)
       }
   }
   var a = 3
   var b = 4
   var fn = obj1.fn
   fn() //Call the function directly, and this points to the window object, and the result will return 7
function fn() {
       return this.a + this.b
   }
   var a = 1
   var b =2
   var obj = {
       a:3,
       b:fn(),
       fn:fn
   }
   var result = obj.fn() //By calling in the form of object, this points to obj object, a=3,b:fn() is equivalent to calling FN method globally, and this in b points to window, so b=3
   console.log(result) // 6
  1. Rule 3: array (class array object) count out the function to call: array [subscript] (), and the context is this array (class array object)
  • Class array objects: all objects whose key names are natural number sequences (starting from 0) and have length attribute
  • The arguments object is the most common class array object, which is a list of arguments to a function
function fun() {
       arguments[3]()
   }
    fun('A','B','C',function() {
        console.log(this[1]) // this points to the arguments class array object 'A','B','C',function(), and the result output is B
    })
  1. Rule 4: for functions in IIFE, the context is window object

(function() {
...
})()

var a = 1
    var obj = {
        a:2,
        fun:(function(){
            var a = this.a; //this in IIFE points to window, then a=1
            return function() {
                // A is inside the function body, then a=1
                // return returns a function
                console.log(a + this.a) // 3
            }
        })()
    }
    obj.fun() //The method of calling this object points to this. obj a=2
  1. Rule 5: the timer and delayer call the function, and the context is the window object

Setinterval (function, time)
SetTimeout (function, time)

var obj = {
        a:1,
        b:2,
        fun() {
            console.log(this.a + this.b) 
        }
    }
    var a = 3
    var b = 4
    setTimeout(obj.fun, 2000); //This points to window, then this a=3,this. b=4
    setTimeout(() => {
        obj.fun() //If the function is called in the form of object point method, this points to obj object, this a=1,this.b=2
    }, 2000);
  1. Rule 6: the context of the event handler is the DOM element that binds the event
DOM element.onclick = function() {
//When there are other functions inside the function, such as timer, the direction of this should be considered
// If necessary, you need to back up this, that is, var_ This = this, which can be used in the internal function_ This points to the DOM you want
 }

3. call and apply

3.1 call and apply can specify the context of the function

Function Call (context)
Function Apply (context)

function sum() {
        console.log(this.chinese + this.math + this.english)
    }
    const person = {
        chinese:98,
        math:100,
        english:95
    }
    sum.call(person)
    sum.apply(person)

3.2 difference between call and apply

  1. When passing parameters, call should separate the parameters with commas, and apply uses an array to store the parameters
  2. The first parameter is the context, and the second parameter is the parameter value of waist wear
function sum(x,y) {
        console.log(this.chinese + this.math + this.english + x +y)
    }
    const person = {
        chinese:98,
        math:100,
        english:95
    }
    sum.call(person,4,5)
    sum.apply(person,[4,5])

5, Constructor

5.1 four steps of calling function with new

new function ()

  1. A blank object is automatically created inside the function body
  2. The context of the function (this) points to this object
  3. The statements in the function body are executed
  4. The function automatically returns the context object, even if the function does not have a return statement

5.2 constructor

  • The function called with new is the constructor
  • Constructor names should be capitalized
  • this of the constructor is not the function itself

5.3 types and examples

  • 'samoye 'is a class, and Dudu is an example
// Person is a class
    function Perosn(name,age,sex) {
        this.name = name
        this.age = age
        this.sex = sex
    }
    // dudu is an instance
    var dudu = new Perosn('toot toot',18,'female')
    // heihei is an example
    var heihei = new Perosn('black',19,'male')

6, Prototype and prototype chain

6.1 prototype object

  • When creating a function, the parser will automatically add an attribute prototype to the function, which corresponds to an object called a prototype object
  • Any function object has a prototype attribute
  • If the function is called as a normal function, the prototype is meaningless
  • If it is called as a constructor, the object (instance) it creates will have an implicit attribute pointing to the prototype object of the constructor. You can__ proto__ Access this implied property
console.log(dudu.__proto__ === Perosn.prototype) //true
  • The prototype of the constructor is the prototype of its instance

6.2 prototype chain search

  • JavaScript stipulates that an instance can manage the properties and methods of accessing its prototype, which is called "prototype chain lookup"
  • The prototype object is equivalent to a common area, which can be accessed by all instances of the same class. Therefore, the public content in the object can be uniformly set into the prototype object
  • When accessing a property or method of an object, it will first look for it in the object itself. If not, it will look for it in the prototype object
// Add a property "hobby" to the prototype object
    Perosn.prototype.hobby = 'run'
    console.log(dudu.hobby) // run
    // Add the property hobby to the heihei hei object
	heihei.hobby = 'eat'
    console.log(heihei.hobby) // eat

6.3 hasOwnProperty()

  • When using in to detect whether an attribute is contained in an object, if it is not in the object but in the prototype, it will also return true
console.log('hobby' in dudu) // true
  • Use hasOwnProperty() to detect whether the object itself contains a property. Only the object itself contains the property will return true
console.log(dudu.hasOwnProperty('hobby')) // false

6.4 end of prototype chain

  • Prototype objects are also objects, so there are prototypes
  • When an object or method is used to find its own property first
    • When it doesn't, it will look for it in the prototype object
    • If there is no prototype in the prototype Object, the prototype of the prototype will be searched until the prototype of the Object object is found (generally, only two layers will be searched)
    • The prototype of the Object object has no prototype. If it is still not found in the Object, it returns undefined
// Detect the location of hasOwnProperty
    console.log(dudu.__proto__.__proto__.hasOwnProperty('hasOwnProperty')) // true
    console.log(Object.prototype.hasOwnProperty('hasOwnProperty')) //true
 console.log(dudu.__proto__.__proto__ === Object.prototype) // true
    console.log(Object.prototype.__proto__) // null
  • The value of the prototype attribute is the object. By default, it has the constructor attribute pointing to the function
function sum(a,b) {
        return a+b
    }
    console.log(sum.prototype.constructor === sum) //true

6.5 adding methods on prototype

  • This can avoid the waste of memory
Perosn.prototype.sayHello = function() {
        console.log(`hello!I am ${this.name}~`)
    }
    console.log(dudu.sayHello === heihei.sayHello) // true
    dudu.sayHello() // hello! I'm doodle~

6.6 succession

  • The key to inheritance: subclasses have all the properties and methods of the parent class, and subclasses can also define their own unique properties and methods
  • Inheritance can be achieved through JavaScript's unique prototype chain feature
 // Parent class
    function Perosn(name,age,sex) {
        this.name = name
        this.age = age
        this.sex = sex
    }
    Perosn.prototype.sayHello = function() {
        console.log(`hello!I am ${this.name},I this year ${this.age}Years old~~`)
    }
    Perosn.prototype.sleep = function() {
        console.log(this.name+'I've already started to sleep zzzzzzzz')
    }
    // Subclass
    function Student(name,age,sex,school,studentId) {
        this.name = name
        this.age = age
        this.sex = sex
        this.school = school
        this.studentId = studentId
    }
    
    // Key statements for implementing inheritance
    Student.prototype = new Perosn()

    Student.prototype.study = function() {
        console.log(this.name+'It's time to prepare for study~~~~~')
    }
    Student.prototype.exam = function() {
        console.log(this.name+'Actively preparing for the exam!!!!!!!!')
    }

    // instantiation 
    var dudu = new Student('toot toot',19,'female','Wang Wang University',201802)

    dudu.sayHello()
    dudu.study()
    dudu.sleep()
    dudu.exam()
    console.log(dudu.studentId)
  • Subclasses can override the methods of the parent class

7, Other

7.1 packaging

  • Number(), String(), and Boolean() are wrapper classes for numbers, strings, and Booleans, respectively
  • Wrapper classes are designed so that basic type values can be obtained from their constructor's prototype
  • The instances of Number(), String(), and Boolean() are all object types
  • The basic type value from new can normally participate in the operation
 var a = new Number(123)
        var b = new String('Muke.com')
        var c  = new Boolean(true)
        console.log(a)
        console.log(typeof a)
        console.log(b)
        console.log(typeof b)
        console.log(c)
        console.log(typeof c)
        console.log('--------------------------------')
        console.log(5 + a)
        console.log(b.slice(0,2))
        console.log(c && true)

7.2 Math objects

  • Power sum square: math pow(),Math.sqrt()
  • Rounding up and down: math ceil(),Math.floor()

7.2.1 Math.round()

  • Round a number to an integer
  • Round to one place after the decimal point
var x = 9.345667
        // Round x to 3 decimal places
        console.log(Math.round(x * 1000) / 1000)

7.2.2 Math.max() and math min()

  • Math.max(): the maximum value in the parameter list
  • Math.min(): the minimum value of the parameter list
  • Using math Max() to find the maximum value of the array -- with the help of apply
    • Math.max() requires that the parameters are separated by commas and cannot be arrays
    • Therefore, with the help of the apply method, the array is passed in without specifying the context
var arr = [2,12,34,546,7]
        var max = Math.max.apply(null,arr)
        console.log(max) // 546

7.2.3 Math.random()

  • You can get decimals between 0 and 1
  • Get the integer in [a,b] interval: parseInt(Math.random() * (b - a + 1)) + a
//    Generate an integer between [3,8]
    console.log(parseInt(Math.random() * 6) + 3)

7.3 Date object

  • You can get the date Object of the current time through new Date(), which is an Object type value
  • You can specify the time object of the date through new Date(yyyy,mm,d), but the month starts from 0, that is, 11 represents December, which is not a time zone
  • In the writing method of new date ('yyyy MM DD ') string, the month starts from 1, and both the month and date should keep two digits, making up for 0. This writing method will calculate the time zone

7.3.1 common methods of time object

7.3.2 time stamp

  • The timestamp represents the number of milliseconds from zero on January 1, 1970 to a certain time
  • Through getTime() or date Parse () can change the date object into a timestamp
  • New date allows you to change a timestamp into a date object
var d = new Date()
    var timestamp1 = d.getTime() // Accurate to milliseconds
    var timestamp2 = Date.parse(d) // Accurate to seconds

Keywords: Javascript Front-end

Added by UKlee on Sun, 06 Mar 2022 11:26:16 +0200