JavaScript advanced part-02 (prototype chain / ES6 class and inheritance)

1. Introduction to three characteristics of object-oriented

  • ​ 1. Encapsulation: encapsulate a specific function in an object and only expose the specified interface to the outside. When the outside world uses it, it only considers how to use the interface, not how to implement it internally (the api learned earlier is actually an encapsulation idea)
  • 2. Inheritance: an object has properties and methods of other objects
  • 3. Polymorphism: multiple states of an object in different situations

2. Three implementation methods of inheritance

2.1 mixed inheritance: traverse all attribute values of the parent object and add them to the child object

  • Features: each time you inherit, you have to execute a loop
  • Application scenario: single object inheritance
//Inheritance: let one object own the properties and methods of another object
        let father = {
            house: {
                address: 'Beijing first ring road',
                price: 100000000
            },
            car: {
                brand: 'Rolls-Royce',
                price: 5000000
            }
        }
        let son = {
            name: 'ikun',
            age: 30
        }

        //1. Mixed type
        //Solution: traverse all attribute values of the parent object and add them to the child object
        //Features: each time you inherit, you have to execute a loop
        //Application scenario: single object inheritance

        for (let key in father) {
           son[key] = father[key]
        }
        console.log(son)

2.2 replace prototype inheritance: take the parent object as the prototype of the child object constructor

  • Feature: member variables before the prototype will be lost
  • Application scenario: multiple object inheritance
let father = {
            house: {
                address: 'Beijing first ring road',
                price: 100000000
            },
            car: {
                brand: 'Rolls-Royce',
                price: 5000000
            }
        }

        function Son(name, age) {
            this.name = name
            this.age = age
        }
        Son.prototype.sayHi = function () {
            console.log('Hello')
        }
        
        /* Replace prototype inheritance: takes the parent object as the prototype of the child object constructor
           Features: used for multi object inheritance, but will overwrite the original prototype
       */
        Son.prototype = father

        console.log(Son.prototype);

        //Instantiate object
        let son1 = new Son('ikun', 30)
        console.log(son1)
        let son2 = new Son('monitor', 20)
        console.log(son2)

2.3 hybrid inheritance: hybrid + replacement prototype

  • Features: traverse all attribute values of the parent object and add them to the prototype of the child object constructor
        //parent object
       let father = {
           house : {
               address:'Wuhan Tiandi',
               price : 10000000
           },
           car:{
               brand:'Rolls-Royce Phantom ',
               price:8000000
           }
       }

       //Sub object constructor
       function Son(name,age){
        this.name = name
        this.age = age
       }

       //Default prototype
       Son.prototype.eat = function(){
           console.log('Eat something')     
       }
       /* Hybrid: hybrid + replacement prototype
            * Traverse the parent object member and add it to the child object constructor prototype
            * Features: multi object inheritance, but does not overwrite the default prototype
       */
       for(let key in father){
           Son.prototype[key] = father[key]
       }

       let son1 = new Son('Cool brother',20)
       let son2 = new Son('ikun',30)
       console.log(son1,son2)

3. (key) prototype chain (bottom foundation of frame)

3.1 prototype chain:

  • Each instance object has its own prototype, and the prototype is also an object and has its own prototype. By analogy, a chain structure is formed, which is called the prototype chain.

3.2 prototype chain access rules: proximity principle

  • Objects give priority to accessing their own members. If they don't have a prototype, find the prototype of the prototype. If they don't have a prototype, find the prototype of the prototype. And so on until the end of the prototype chain is null If the property is not found, get undefined, and the method reports an error undefined is not a function
  • The member instance object in the prototype object can be used directly because there are members in the instance object_ proto_ Property points to the prototype object

3.3 role of prototype chain: Inheritance

  • js language realizes object-oriented inheritance through prototype chain

Only objects have prototypes. Here, we must distinguish the basic data types string, number and Boolean from the basic wrapper types (special reference type objects) string, number and Boolean. Don't confuse them

<script>
        /* 
        1.Prototype chain: every object has__ proto__ Point to your own prototype. The prototype is also an object and has its own characteristics
        __proto__Point to the prototype of the prototype, and so on to form a chain structure, which is called the prototype chain.

        2.Rules for object access to members in prototype chain: proximity principle
            When accessing members of an object, first see if you have one. If there is, visit, if not, see if there is a prototype. The prototype has a visit,
            If not, access the prototype of the prototype, and if not, continue to look up. And so on, find the end point of prototype chain: null
            Not yet. If it is an attribute, get undefined. If it is a method, report xxx is not defined 
         */
        
        //1. Constructor
        function Person(name,age){
            this.name = name;
            this.age = age;
        };

        //2. Prototype object
        Person.prototype.sayHi = function(){
            console.log('If life is just like the first sight, why does the autumn wind draw a fan');
        };

        Person.prototype.type = 'mammal';

        //3. Instantiate object
        let p1 = new Person('Again and again',18);
        console.log(p1);

        //Please say the following code execution results
        console.log(p1.name);//It p1 has its own name attribute
        console.log(p1.type);//Mammalian p1 has no type, but the prototype of p1 has
        console.log(p1.hobby);//undefined p1 has no hobby and no prototype
        p1.sayHi();// If life is just like the first sight, why does the autumn wind draw a fan p1? I don't have this method. The prototype has
       // p1.eat();// The error XXX is not defined P1 does not have this method, nor does the prototype

       //Why not report an error? p1 does not have this method, nor does the prototype, but the prototype of the prototype does
        p1.toString();

        //View the prototype chain of p1
        console.log(p1.__proto__.constructor);//Person
        console.log(p1.__proto__ === Person.prototype);//true

        //View the prototype of p1
        console.log(p1.__proto__.__proto__.constructor);//Object
        console.log(p1.__proto__.__proto__ === Object.prototype);//true

        //View the prototype of p1
        console.log(p1.__proto__.__proto__.__proto__);//null

    </script>

4. Prototype chain of array

//1.Array
    let arr = new Array(10,20,30);
    console.log ( arr );
    //View the prototype of arr
    console.log ( arr.__proto__.constructor );//Array
    console.log ( arr.__proto__ === Array.prototype );
    //View the prototype of arr
    console.log ( arr.__proto__.__proto__.constructor );//Object
    console.log ( arr.__proto__.__proto__ === Object.prototype );//true

5. Prototype chain of date

//2.Date
    let date1 = new Date();
    //Details: Date object directly to console Log will be converted to string, and console.com is required to view the object Dir print
    console.dir(date1);
    console.log ( date1.__proto__ === Date.prototype );//true
    console.log ( date1.__proto__.__proto__.constructor );//Object
    console.log ( date1.__proto__.__proto__ === Object.prototype );//true

6.String object prototype chain

//3.String
    let str = new String('123');
    console.log ( str );
    console.log ( str.__proto__ === String.prototype );//true
    console.log ( str.__proto__.__proto__.constructor );//Object
    console.log ( str.__proto__.__proto__ === Object.prototype );//true

7.DOM object prototype chain

    <div class="box">div Box</div>
    <p class="pp">p label</p>
    <script>
        //Get dom object
        let box = document.querySelector('.box')
        let pp = document.querySelector('.pp')
    </script>

4.instanceof operator

  • instanceof keyword (operator): detect whether the prototype of the constructor (prototype attribute) appears in the prototype chain of an instance object
    In: true
    Not in: false
  • Instanceof syntax: instance object instanceof constructor
  • instanceof operator: limits the data type of function parameters
    For example:... not of type... The function parameter data type is wrong
        //Array instance object
        // arr->Array.prototype->Object.prototype->null
        let arr = [10,20,30]

        console.log( arr instanceof Array )//true
        console.log( arr instanceof Object )//true
        console.log( arr instanceof String )//false
       //2. Examples
    //According to the instanceof syntax: the Function on the left represents the object and the Function on the right represents the constructor
    //Function prototype chain function object - > function prototype->Object. prototype->null
    console.log ( Function instanceof Function );//true
    console.log ( Function instanceof Object );//true

    //3. Examples
    //According to the instanceof syntax: the Object on the left represents the Object, and the Object on the right represents the constructor
    //Object prototype chainobject - > function prototype->Object. prototype->null
    console.log ( Object instanceof Object );//true
    console.log ( Object instanceof Function );//true     

        //Error: the parameter is not a node   
        //The instanceof keyword is generally used in functions to limit the data type of parameters
        //For example, the appendChild() parameter can only be a node node. If you pass other types, an error will be reported. The bottom layer will use instanceof to detect the parameter data type
        let h1 = document.createElement('h1')
        h1.innerText = 'I am h1 label'
        document.body.appendChild(h1)

5.ES6 class and inheritance (class / extensions / super)

51.class keyword:

Function: declare a class function (equivalent to the constructor of ES5, but the readability of the code is greatly improved)

  • 1. Write all constructors and prototypes in a brace to improve code readability
  • 2. You must use new to call the class function, otherwise an error will be reported to improve the code specification

class keyword syntax:

        class Constructor name{
                    constructor(){
                     //(1) Write the constructor code here
                    };
                    //(2) The methods in the prototype are written below
                    eat(){
                    };
                    play(){
                    };
                };       

In fact, the essence of class is another way to write the constructor. The underlying principle remains unchanged. The essence is to add members to the prototype. If you use class, you can continue to use the prototype of ES5

5.2 extensions keyword

  • Role: class inheritance

  • Syntax: class subclass function extends parent class function {}

  • Bottom layer: replace the prototype inheritance of the prototype object (the prototype of the child constructor will not be overwritten)

    • Replace prototype:
      s1.proto = Person.prototype (will overwrite S1 the original prototype)
    • extends keyword replaces the prototype of the prototype:
      s1.proto.proto === Person.prototype (does not overwrite S1 the original prototype)
 //ES6 class function
        class Person{
            //1. Constructor
            constructor(name,age){
                this.name = name
                this.age = age
            }

            //2. Prototype method
            eat(){
                console.log('Eat something')
            }
        }

        //3. Instance object
        let p1 = new Person('ikun',30)
        console.log( p1 )

        /* extends Keyword function: class inheritance 
        Syntax: class subclass function extends parent class function
        Bottom layer: replace prototype inheritance (the prototype of the child constructor will not be overwritten)
            The alternative prototype we talked about in class: s1__ proto__ =  Person. Prototype (will overwrite s1 the original prototype)
            extends Keyword replace the prototype of the prototype:
                s1.__proto__.__proto__ === Person.prototype (Will not overwrite s1 the original prototype)
        */
       class Student extends Person{
            //Child constructor prototype method
            learn(){
                console.log('I had a good time today')
            }
       }

       let s1 = new Student('Shuang Chen',20)
       console.log(s1)
       s1.learn()//Call the subclass's own method
       s1.eat()//Call the parent class method (inheritance: have all members of the parent class)

5.3super: calling parent class in subclass

  • (1) Application: if a subclass wants to write its own constructor, it must first call the constructor of the parent class, otherwise the program will report an error
  • (2) Syntax: super()
Application scenario: written in subclass constructor Method
                 class Subclass function extends Parent class function{
                    //Subclass constructor
                    constructor(name,age,score){
                        super(name,age)
                        this.score = score
                    }
                    //Subclass prototype method
                    learn(){
                        
                    }
                }
        //Parent function: Person
        class Person{
            //Constructor
            constructor(name,age){
                this.name = name
                this.age = age
            }

            //Prototype method
            sayHi(){
                console.log('i love you')  
            }
        }  
    
        //Subclass function: teacher
        class Teacher extends Person{
            //Constructor
            constructor(name,age,className){
                //Parent method
                super(name,age)
                this.className = className
            }

            //Subclass prototype
            learn(){
                console.log('One day as a teacher, one life as a friend') 
            }
        }

        let t1 = new Teacher('ikun',30,'71 stage')
        console.log(t1)//Teacherage: 30classname: "phase 71" name: "ikun"[[Prototype]]: Person
        
    </script>

6. Function supplement

6.1 keyword in function: arguments

  • Function: arguments: get all the arguments (pseudo array) of the function
  • Scenario: for example, the bottom layer of arr.push() is to obtain arguments with arguments
       function fn(a,b){
        console.log(a,b)//10,20
        console.log( arguments )//Get all arguments of the function
       }

       fn(10,20,30,40,50)

6.2.rest parameters (remaining parameters):... Formal parameter name

  • Function: get all remaining parameters (true array)
  • Scenario: in most cases, the remaining parameters can replace arguments
 function fn(...b){
        console.log(b)//Get all remaining parameters
        console.log( arguments )//Get all arguments of the function
       }

       fn(10,20,30,40,50)

6.33. Function default parameters:

ES5: logic or interrupt
ES6: formal parameter = default value

  • 1. The essence of function parameter passing is that the real parameter assigns a value to the formal parameter
  • 2. The number of function parameters and arguments can be different, but they will be assigned one by one in order
 function fn(a=10,b=20){
            //Find true: the left is true and returns the value on the left. Conversely, return the value on the right
            // a = a || 10
            // b = b || 20
            console.log(a)//5
            console.log(b)//20
        }    
        fn(5)//Bottom layer fn(5,undefined)

7. Summary:

7.1. Three characteristics of object oriented

  • a. Encapsulation: encapsulating a function into an object or function
  • b. Inheritance: one object owns all member variables (properties and methods) of another object
  • c. Polymorphism: multiple states of an object in different situations

7.2. Several ways to implement inheritance

  • a. Mixed inheritance

    • Solution: traverse all attribute values of the parent object and add them to the child object
    • Disadvantages: each time you inherit, you have to execute a loop
    • Application scenario: the parent object has only one child object
  • b. Replace prototype

    • Solution: prototype the parent object as a child object constructor
    • Disadvantage: the member variables before the prototype will be lost
    • Application scenario: Customizing built-in objects
  • c. Hybrid (mixed + replacement prototype)

    • Solution: traverse all attribute values of the parent object and add them to the prototype of the constructor
    • Application scenario: parent object has multiple child objects

7.3. Prototype chain

  • Prototype chain: every object has a prototype, and the prototype itself is an object, so the prototype has a prototype, and so on to form a chain structure, which is called prototype chain
  • Access rules of objects in prototype chain: proximity principle
    • When accessing an object member variable, you will first look it up from your own properties. If there is, you will access it, if there is no, you will access your prototype. If there is no, you will access the prototype of the prototype, and so on. If you access the top of the prototype chain or there is no, the program will report an error XXXX is not defined
    • Special case: object The prototype object of prototype is null
  • . The function itself is also an object
    • Constructors belong to functions

7.4.instanceof operator

  • Syntax: object instanceof constructor
  • Function: detect whether the prototype prototype of the constructor is on the prototype chain of this object

7.5. What technology does JS language use to realize object-oriented inheritance

  • Answer: prototype chain

7.6 what is the end point of the prototype chain

  • Answer: null

Keywords: Javascript Front-end

Added by larus@spuni.is on Mon, 27 Dec 2021 11:02:49 +0200