Web front end lesson 38 – JS classes and objects, inheritance, design patterns

Time:2021-7-27

1. Foundation

Class is an abstract, non-existent description that represents the common characteristics of a thing

An object is a concrete, actually existing, individual in a class

JavaScript is a typical “process oriented thinking” language. There are no concepts of classes and objects in the language,

However, because JavaScript often solves the problem of “object-oriented thought”, JavaScript uses some methods to simulate the characteristics of object-oriented thought.

2. Class creation

Constructor, by   The function of the object generated by the new command is called the constructor, which is generally capitalized

The function of the new command is to create an object first, and then let the object call the constructor. Therefore, this in the constructor points to   New created object

Syntax example:

    function Student(name, age, sex){

      this .name=name;

      this .age=age;

      this .sex=sex;

    };

    var Lili = new Student(‘Lili’, 20, ‘female’);

In the above code, the function   Student represents the class name and assigns values to the properties of the class by passing arguments. The new command constructs these key value pairs as objects and assigns them to variables

Note that this method is only   JS is one of many ways to create classes, and it is not the best way to create classes

3. Object oriented idea

Object oriented (OOP), create an object, let the object have the ability to do something (give object properties and methods), and then command the object to do something (encapsulation, inheritance, polymorphism)

Process oriented (POP), analyze all the steps to solve the problem, build them into a function, and then implement these steps in a certain order (sequence, selection, cycle)

The core of OOP is how to build an object, that is, “object encapsulation”!

4. Packaging

It refers to the process of constructing a class with certain characteristics to obtain an object that meets the requirements by instantiating it

Features of the package:

Public, the attributes and methods in an object that can be accessed directly outside the object, are called public attributes and methods

Private: the properties and methods in an object that can only be used inside the object are called private properties and methods

In the constructor, add public attributes and methods to the class by means of “this. Attribute”

The content added by this.property can be accessed directly outside the object

In the constructor, add local variables and closures to add private properties and methods to the class

Local variables ensure that external objects cannot be obtained directly, and closures ensure that external objects can be obtained indirectly

For the common attribute of all objects, in order to reduce the repeated transmission of the same attribute value when constructing the object, the   The prototype attribute is defined uniformly

Syntax: class name. Prototype. Attribute with the same attribute value=   Attribute value;

5. Prototype

JS provides the function with an object type attribute called   Prototype

The prototype belongs to the function and does not need to be created. It exists by default

Syntax: class. Prototype. Property = ‘value’;

Note that JS provides a mechanism. If an object is created through a class, when the accessed attribute is not found in the object,

It will find the prototype property of the class that created the object. If it can be found, it will be deemed that the current object has this property.

In essence, prototypes exist to add common attributes to class objects

The use of prototypes can effectively save memory space. The properties and methods created by prototypes can be accessed by all objects created by this class

6. Constructor syntax summary

Function classname (para1, para2,...) {// the first letter of class name must be capitalized var privateproperty = 'value'; // define private property var privatefunc = function() {} // define private method this.publicproperty1 = para1; // define the public property this.publicproperty2 = para2;     this.publicFunc = function(){ }; // define public methods (privileged functions that can read and write privateproperty)
... ...  }  ClassName.prototype.publicProperty3 = 'value3'; // define the prototype (shared) attribute and attribute value classname. Prototype. Publicfunc = function() {}; // define prototype (shared) methods

var   obj =   new   Classname (argument 1, argument 2,…); / / create objects through classes

7. Prototype properties

Structure: a prototype is an object. There are usually two properties in the prototype

①   Constructor, this attribute points to the class itself (indicating which class the current prototype belongs to)

②   Prototype pointing_ proto_, This property points to the prototype itself and is provided to objects created through the class

Role: create public attributes and public methods of classes to serve the creation of objects

Save memory space. You don’t have to allocate memory for public properties and public methods for each object

Disadvantages: arrays cannot be saved in the prototypereference typeData

Because the problem of address transmission will lead to the chain change of modification

For example, through   obj .publicProperty .pop();   Delete the elements in the common attribute array,

This will cause other objects to access the prototype. Publicproperty   Array is also missing this element

8. Prototype chain

The prototype chain consists of the object’s “_ proto_” Prototypes of constructors for properties and objects “_ proto_” The chain structure composed of attributes is called prototype chain

The top of the prototype chain is   Object object, object object has no “_ proto_” Property, or its “_ proto_” Property points to itself

Prototype chain function: when accessing an object’s property or method, first find out whether it owns the property or method in the object itself,

If it is not found, it will look up step by step along the prototype chain until the object is found

If this property or method is found at any level, it is considered that the object owns this property or method (inheritance)

The prototype chain is created, and the prototype of the function is set as the object (instance) of another function

Syntax example: classname101. Prototype = New    ClassName1 ;

9. Succession

In an object-oriented language, the property that a subclass can use the properties and methods of its parent class without declaration is called inheritance

In essence, JavaScript needs some kind of language, not a method of inheritance

Chain inheritance example:

function RichMan() {}
    RichMan.prototype.money='billions of pounds';
    var father=new RichMan();   // Create an instantiated object of the parent class

    function Son() {}
    Son.prototype=father;       // Create subclass inheritance relationship
    
    var boy=new Son();          // Create subclass instantiation object
    console.log(boy.money);     //billions of pounds

Existing problems:

    ① Prototype chain inheritance, subclass instantiation cannot pass parameters to the parent constructor, but can directly access the prototype properties of the parent

     Construction inheritance, you can only access the instance properties of the parent class. When instantiating, you can pass parameters to the constructor of the parent class, but you cannot access the prototype properties and methods of the parent class

②   Prototype chain, inheritance, subclass   Prototype   The constructor attribute is actually the parent class   Prototype   Constructor attribute, which is unreasonable

Constructor, subclass   Prototype   The constructor attribute is the subclass itself, and so is the parent class, but the subclass inherited by the constructor cannot enjoy the prototype attribute and method of the parent class

Construction inheritance example:

function RichMan(fcash,fhouse,fcar) {
        this.cash=fcash;
        this.house=fhouse;
        this.car=fcar;
    }
/*    RichMan.prototype.money='billions of pounds';
    var father=new RichMan();   // Create an instantiated object of the parent class*/

    function Son(scash,shouse,scar) {
        RichMan.call(this,scash,shouse,scar);      // Create subclasses and construct inheritance relationships
    }
    var john=new Son(1,2,3);        // You can access the parent class instance property, but not the prototype property
    var dancy=new Son(4,5,6);

10. Combination inheritance

In order to solve the shortcomings of “prototype chain inheritance” and “construction inheritance”, two inheritance methods are used simultaneously when creating subclass inheritance, namely composite inheritance

1 
 2     function RichMan(fcash,fhouse,fcar) {
 3         this.cash=fcash;
 4         this.house=fhouse;
 5         this.car=fcar;
 6     }
 7     RichMan.prototype.money='billions of pounds';
 8     // var father=new RichMan();   // Create an instantiated object of the parent class
 9 
10     function Son(scash,shouse,scar) {
11         RichMan.call(this,scash,shouse,scar);   // Create a construction inheritance relationship
12     }
13     Son.prototype=new RichMan();        // Create a chain inheritance relationship
14     var john=new Son(1,2,3);
15     var dancy=new Son(4,5,6);
16     console.log(john);                 //Son {cash: 1, house: 2, car: 3}
17     console.log(dancy.money);          //billions of pounds
18 
19 /*    Son.prototype=father;       // Create subclass inheritance relationship
20     var boy=new Son();          // Create subclass instantiation object
21     console.log(boy.money);     //billions of pounds*/
22

Disadvantages of combined inheritance:

In the subclass, we call the parent class constructor two times, one for building inheritance, one for chain inheritance, the other is initialization of instance property two times.

However, this disadvantage is not fatal. When subclasses are instantiated, the instance properties of constructed inheritance cover the instance properties of chain inheritance, but consume more memory.

Parasitic combinatorial inheritance

Core idea: cut off the instance attribute of the parent class through parasitism, so that the instance attribute / method will not be used again when calling the construction of the parent class twice.

1 
 2 
 3     
 4 succession
 5 
 6 
 7 
 8 
 9     function RichMan(fcash,fhouse,fcar) {
10         this.cash=fcash;
11         this.house=fhouse;
12         this.car=fcar;
13     }
14     RichMan.prototype.money='billions of pounds';
15     // var father=new RichMan();   // Create an instantiated object of the parent class
16 
17     function Son(scash,shouse,scar) {
18         RichMan.call(this,scash,shouse,scar);   // Create a subclass construction inheritance relationship
19     }
20     // Son.prototype=new RichMan();       // Create a chain inheritance relationship
21     Son.prototype.constructor=Son;        // Point the subclass prototype attribute 'constructor' to the subclass itself!
22 
23 (function() {// create a self executing function and nest an empty constructor medi,
24 function medi() {} // insert an empty constructor into the prototype chain as an intermediate node, that is, the atomic class becomes a descendant
25         Medi.prototype=new RichMan();   // In this way, it is avoided to instantiate the attributes and methods of the parent class twice every time the child (grandchild) class is instantiated
26         Son.prototype=new Medi();       // That is to use this parasitic way to replace the original direct "chain inheritance" relationship
27     }());
28 
29     var john=new Son(1,2,3);
30     var dancy=new Son(4,5,6);
31     console.log(john);                 //Son {cash: 1, house: 2, car: 3}
32     console.log(dancy.money);          //billions of pounds
33 
34 /*    Son.prototype=father;       // Create subclass inheritance relationship
35     var boy=new Son();          // Create subclass instantiation object
36     console.log(boy.money);     //billions of pounds*/
37 
38 
39

 

11. Design mode

Design mode   Pattern) is a set of repeatedly used, well-known and classified code design experience (template)

Function: improve code reusability, make code easier to be understood by others, and improve code reliability,

Design pattern makes code writing truly engineering, which is the cornerstone of software engineering, just like the structure of a building

Common types:

①   Factory mode

②   Constructor Pattern

③   Prototype mode

④   Mixed mode

⑤   Dynamic prototype mode

12. Factory mode

function RichMan(fcash,fhouse,fcar) {
            var richMan={};             // Defines a local variable of type object
            richMan.cash=fcash;         // Directly define the properties of internal objects
            richMan.house=fhouse;
            richMan.car=fcar;
            return richMan;             // Take the internal object as the return value of the calling function
        }
        var man=RichMan('muchCash','bigHouse','luxuryCar');
        console.log(man);
        console.log(man instanceof RichMan);        // The return value is false

Factory pattern is a design pattern often used in software development

Instanceof method whether an instance belongs to a class.

The biggest problem with objects created through factory mode is that it is impossible to determine which class they belong to!

13. Constructor mode

function RichMan(fcash,fhouse,fcar) {
            this.cash=fcash;         // Define this attribute
            this.house=fhouse;
            this.car=fcar;
        }
        //Create an object with the new command
        var man=new RichMan('muchCash','bigHouse','luxuryCar');
        console.log(man);
        console.log(man instanceof RichMan);        // The return value is true

The biggest difference between constructor and factory mode is:

Instead of creating an object, it is created through   The new command implicitly creates an object

Then let the implicit object actually execute the constructor, so the   This points to the implicit object

The object created by the constructor can clearly determine which class it belongs to

Constructor must be used to create objects   New command, the first letter of the function name is usually capitalized

The biggest problem of constructor mode is that it can not effectively save memory when facing the common attribute values of subclass objects!

14. Prototype model

function RichMan(fcash,fhouse,fcar) {}
        //Use the prototype method to define the common properties of the class
        RichMan.prototype.cash='muchCash';
        RichMan.prototype.house='bigHouse';
        RichMan.prototype.car='luxuryCar';
        //Create an object with the new command
        var man=new RichMan();
        man.house='manyHouse';  // For the same attribute, different attribute values are assigned separately
        console.log(man);
        console.log(man instanceof RichMan);        // The return value is true

Disadvantages: when dealing with public attributes with different attribute values, it increases the space occupation of memory!

15. Mixed mode

function RichMan(fcash,fhouse,fcar) {
            this.cash=fcash; 
            this.house=fhouse;
            this.car=fcar;
        }
        RichMan.prototype.advantage=function () {
            Console.log ('counting money till hand cramps')
        }
        //Create an object with the new command
        var man=new RichMan('muchCash','bigHouse','luxuryCar');
        console.log(man);
        man.advantage();

16. Dynamic prototype mode

function RichMan(fcash,fhouse,fcar) {
            this.cash=fcash;
            this.house=fhouse;
            this.car=fcar;
            //Use "lazy loading" to define the prototype of common attributes
            if (typeof RichMan._initialized=='undefined'){
                RichMan.prototype.advantage=function () {
                    Console.log ('counting money till hand cramps')
                }
                RichMan._initialized=true;
            }
        }
        //Create an object with the new command
        var man=new RichMan('muchCash','bigHouse','luxuryCar');
        console.log(man);
        man.advantage();

  Lazy loading: the memory space is loaded and occupied only when it is used. It is equivalent to nonexistence before it is used

The dynamic prototype pattern is very similar to the hybrid pattern. Both of them are to solve the problem that all content in the prototype pattern is public

The dynamic prototype pattern is characterized by,

By judging the “. Of a class_ initialized”   Type of property, and then judge whether this class has been instantiated,

If it has not been instantiated, it will be released on the first call (initialization) and the property value will be written as   true。

  “._initialized”Property is a private property owned by each class. It is only used to indicate whether the class has been instantiated. It is a read-write property of boolean type.