JavaScript advanced tutorial (object-oriented programming)

Posted by GiaTuan on Mon, 21 Feb 2022 11:45:46 +0100

catalogue

object-oriented programming

Classes and objects in ES6

Constructors and prototypes

Object prototype__ proto__

Constructor constructor

The relationship among constructor, instance and prototype object

Prototype chain

Extend built-in objects

inherit

object-oriented programming

There are two major programming ideas: process oriented and object-oriented;

Pop (process oriented programming)

Process oriented is to analyze the steps needed to solve the problem, and then use functions to realize these steps step by step. When using, you can call them one by one;

The elephant is put into the refrigerator. From the perspective of facing the process, it is necessary to open the refrigerator door, put in the elephant and close the refrigerator door

Object oriented programming (OOP)

Object oriented is to decompose transactions into objects, and then divide and cooperate among objects; The problem is divided by object function, not steps; In the idea of object-oriented program development, each object is the function center and has a clear division of labor;

Object oriented programming has the advantages of flexibility, code reusability, easy maintenance and development, and is more suitable for large-scale software projects with multi person cooperation;

It has the characteristics of encapsulation, inheritance and polymorphism;

Put the elephant into the refrigerator. From the perspective of object-oriented, we should first find out the objects and write out the functions of these objects; Such as elephant object, refrigerator object;

Comparison between object-oriented programming and object-oriented programming:

Process oriented

object-oriented

advantage

Higher performance than object-oriented, suitable for things closely related to hardware, such as process oriented programming adopted by single chip microcomputer

Easy to maintain, reuse and expand. Low coupling system can be designed to make the system more flexible and easier to maintain

shortcoming

No object-oriented, easy to maintain, easy to reuse and easy to expand

Lower performance than object-oriented

Object oriented thinking characteristics:

1. Extract (Abstract) the attributes and behaviors shared by objects, organize (encapsulate) them into a class (template);

2. Instantiate the class and get the object of the class

In object-oriented programming, we consider which objects are there. According to the characteristics of object-oriented thinking, we constantly create objects, use objects, and command objects to do things;

Classes and objects in ES6

  • object

In JavaScript, an object is an unordered collection of related attributes 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 (noun);

Method: the behavior of things is expressed by means in the object (verb);

  • Class:

The concept of class is added in ES6. You can declare a class with the class keyword, and then instantiate the object with this class;

Class and object relationships:

Class abstracts the common part of an object, which generally refers to a large class;

Object refers specifically to a, instantiating a specific object through a class;

Create class

class Class name { // Do not use parentheses for class names here

// Function body in class

}

Create instance:

var xx = new Class name(); // Class must instantiate the object with new

Class constructor constructor

The constructor() method is the constructor of the class (the default method). It is used to pass parameters, return the instance object, generate the object instance through the new command, and call the method automatically. If the definition is not displayed, a constructor() will be automatically created inside the class.

 <script>
        // Create class
        class Person {
            constructor(uname, sex, age) {
                this.uname = uname;
                this.sex = sex;
                this.age = age;
            }
        }
        // Create instance object
        var xm = new Person('Xiao Ming', 'female', 19);
        var xs = new Person('Small shirt', 'male', 18);
        console.log(xm, xs);
 </script>

The output results are as follows:

Add method to class:

All functions in the class do not need to write function, and there is no need to add symbol separation between multiple function methods;

 <script>
        // Create class
        class Person {
            constructor(uname, sex, age) {
                    this.uname = uname;
                    this.sex = sex;
                    this.age = age;
                }
                // Add method to class
            Say() {
                console.log('My name is' + this.uname, 'Gender' + this.sex, 'this year' + this.age);
            }
        }
        // Create instance object
        var xm = new Person('Xiao Ming', 'female', 19);
        var xs = new Person('Small shirt', 'male', 18);
        console.log(xm, xs);
        // Call method by instance
        xm.Say(); // My name is Xiao Ming, female, 19 this year
        xs.Say(); // My name is Xiaoshan male. I'm 18 this year
    </script>

inherit

Inheritance refers to that a subclass can inherit some properties and methods of the parent class. The syntax is as follows:;

class Father {
  // Parent class
}
class Son extends Father {
  // The subclass inherits the parent class
}

Look at the following error example:

<script>
        class Father {
            constructor(x, y) {
                this.x = x;
                this.y = y;
            }
            sum() {
                console.log(this.x + this.y);
            }
        }
        class Son extends Father {
            constructor(x, y) {
                this.x = x;
                this.y = y;
            }
        }
        var son = new Son(1, 2);
        son.sum();
</script>

When running this code, the following error will be reported:

Uncaught ReferenceError: Must call super constructor in derived class before accessing 'this' or returning from derived constructor
    at new Son (ObjTsting.html:24:17)

This is because the sum method of the parent class cannot be used in the subclass. In the parent class method, this X and this This in Y refers to the parent class, while in the parameters passed from the child class, this X and this Y refers to subclasses, all of which will report errors;

How to inherit the parameters and methods in the parent class? In this case, the super keyword is required~

super keyword

It is used to access and call the function on the parent class of the object. You can call the constructor of the parent class or the ordinary function of the parent class. The above example can be transformed into:

 <script>
        class Father {
            constructor(x, y) {
                this.x = x;
                this.y = y;
            }
            sum() {
                console.log(this.x + this.y);
            }
        }
        class Son extends Father {
            constructor(x, y) {
                super(x, y); // Call the constructor of the parent class
            }
        }
        var son = new Son(1, 2);
        son.sum(); // 3
</script>

Inheritance means that if a subclass has properties and methods, the properties and methods of the subclass are used. If none, the methods of the parent class are inherited;

The subclass uses super in the constructor, which must be put in front of this (that is, the constructor of the parent class must be called first, and then the constructor of the subclass must be used);

<script>
        class Father {
            constructor(uname, sex) {
                this.uname = uname;
                this.sex = sex;
            }
        }
        class Son extends Father {
            constructor(uname, age) {
                super(uname); // Call the constructor of the parent class (uname)
                this.age = age; // Define properties unique to subclasses
            }
        }
</script>

The common attributes and methods in the class must be used with this; This in the constructor refers to the created instance object; This points to the person who calls the method in the class;

In ES6, classes do not have variable promotion, so you must first define classes before you can instantiate objects through classes;

Constructors and prototypes

Constructors and prototypes existed before ES6 came out and were replaced by classes; Before ES6, objects were not created based on classes, but used a special function called constructor to define objects and their characteristics.

There are three ways to create objects:

1. Object literal

2,new Object()

3. Custom constructor

<script>
        var obj1 = {}; // Create objects by literal
        var obj2 = new Object(); // Create objects with new
        function Obj3(uname, age) { // Creating objects with constructors
            this.uname = uname;
            this.age = age;
            this.sing = function() {
                console.log('This is the method contained in the constructor');
            }
        }
        var dog = new Obj3('puppy', 1);
        var cat = new Obj3('kitten', 1.5);
</script>

Constructor is a special function, which is mainly used to initialize the object, that is, assign the initial value to the object member variable. It is always used with new. They can extract some public attributes and methods from the object and then encapsulate them into this function;

In JS, you should pay attention to the following two points when using constructors:

1. Constructor is used to create a certain type of object, and its first letter should be capitalized;

2. Constructors need to be used with new to make sense

new does four things when executing:

1. Create a new empty object in memory;

2. Let this point to the new object;

3. Execute the code in the constructor and add properties and methods to the new object;

4. Return this new object (so return is not required in the constructor)

Instance members and static members

The properties and methods in the constructor are called members, and members can be added;

Instance members are members added through this inside the constructor; Instance members can only be accessed through instantiated objects; Instance members cannot be accessed through constructors;

Static members and members added on the constructor itself; Static members can only be accessed through constructors

<script>
        function Obj3(uname, age) { // Creating objects with constructors
            this.uname = uname;
            this.age = age;
            this.sing = function() {
                console.log('This is the method contained in the constructor');
            }
        }
        var dog = new Obj3('puppy', 1);
        console.log(dog.uname); // You can only access instance members through instantiated objects
        console.log(Obj3.uname); // undefined cannot access instance members through constructors
        // Static members are members added to the constructor itself. Static members can only be accessed through the constructor
        Obj3.sex = 'male';
        console.log(Obj3.sex); // male
</script>

Constructor problem

Constructor method is easy to use, but there is a problem of wasting memory;

Different instance objects will open up multiple spaces for storing the same function, which will cause a waste of memory;

Since the instance object is constructed from the same object, the function and attribute should be shared by all objects. JavaScript stipulates that each constructor has a prototype attribute pointing to another object. Note that this prototype is an object, and all properties and methods of this object will be owned by the constructor. Therefore, those invariant methods can be defined directly on the prototype, so that all object instances can share these methods.

Object prototype__ proto__

Objects have a property__ proto__ The prototype object that points to the constructor. The reason why we can use the properties and methods of the constructor prototype object is that the object has__ proto__ The existence of prototypes.

  • __ proto__ Object prototype and prototype object prototype are equivalent
  • __ proto__ The significance of object prototype is to provide a direction or a route for the object search mechanism, but it is a non-standard attribute. Therefore, this attribute can not be used in actual development. It only internally points to the prototype object prototype, as shown in the following diagram:

Constructor constructor

Object prototype (_proto_) And the prototype object of the constructor have a property constructor property. Constructor is called the constructor because it refers to the constructor itself.

It is mainly used to record which constructor the object refers to. It can make the prototype object point to the original constructor again.

<script>
        function Obj3(uname, age) { // Creating objects with constructors
            this.uname = uname;
            this.age = age;
        }
        Obj3.prototype = {
            sing: function() {
                console.log('wangwang');
            }
        }
        var dog = new Obj3('puppy', 1);
        console.log(Obj3.prototype); 
        console.log(dog.__proto__);
        console.log(Obj3.prototype === dog.__proto__); // true
</script>

The relationship among constructor, instance and prototype object

Prototype chain

(the picture comes from the front-end tutorial of black horse programmer pink ~)

As long as it is an object, there is a prototype pair;

When accessing the properties (including methods) of an object, first find out whether the object itself has the property;

If not, find its prototype (that is, the prototype object pointed to by _proto _);

If not, find the prototype of the prototype Object, and so on until the Object is found;

__ proto__ The significance of object prototype is to provide a direction, or a route, for the object member search mechanism

Extend built-in objects

You can extend and customize the original built-in object through the prototype object, such as adding a custom even sum function to the array;

<script>
        console.log(Array.prototype);
        Array.prototype.sum = function() {
            var sum = 0;
            for (var i = 0; i < this.length; i++) {
                sum += this[i];
            }
            return sum;
        }
        var arr = [1, 2, 3, 4];
        console.log(arr.sum()); // 10
</script>

Note: array and string built-in objects cannot override the operation array Prototype = {}, can only be array prototype. XXX = method of function() {}

inherit

Similarly, there was no extends inheritance before ES6. We can implement inheritance through constructor + prototype object simulation, which is called composite inheritance;

  • Using the call() method

Call the call() method to modify the this point when the function is running. The syntax is as follows:

Function name.call(thisArg, arg1, arg2,....)

Among them, thisArg is the object of the current calling function this, and args is the other parameter passed.

<script>
        function fn(x, y) {
            console.log('Look at this number');
            console.log(this);
        }
        var o = {
            sum: 12
        }
        fn.call(o, 1, 2); // this points to o and contains sum
</script>

Topics: Javascript Front-end html Interview