Object oriented design of nodejs tutorial

Learning background

Object oriented programming is learning programming to find objects. en... I felt that for a long time, but I haven't found it yet. Maybe it's not pious enough.

To get back to business, learning object-oriented plays a vital role in our learning programming. In the early days of programming, we completed the programming with the idea of process-oriented. It is a process centered programming idea, which focuses on a process of program operation. Compared with a mathematical calculation, reading and writing a file, we can realize the software requirements as long as we do this process well. However, with the increasing complexity of software functions, it will be difficult to use process oriented programming. Therefore, the idea of object-oriented programming is very important. It lets us not only focus on the process, abstract some parts of the program into an entity, and then consider the functions and attributes of each entity separately. Let these individual entities work together to realize software functions.

Object oriented features

  • 1. Encapsulation
    Encapsulation is to package the behaviors (Methods) of the attributes of things into one category. This class has common attributes and behaviors. For example, we encapsulate animals into a category and roughly define bits

      ```
      class animal{
      Attributes: fur
      
      Behavior: eating
      Behavior: sleep
      }
      ```
      Then, the animals we define have hair, eat and sleep (of course, the attributes and behaviors of animals in nature are far more than these. Usually, we only encapsulate the attributes and behaviors considered in the program). Then we'll encapsulate a simple animal.
    
  • 2. Inherit
    In the process of encapsulation, we found a class B with the same attributes as class a but a little special. This category has common attributes and behaviors, but it also has special attributes and behaviors. We usually think that class B inherits from class A. In the above classification of animals, we newly encapsulate the new categories "dog" and "cat"

	class dog extend animal{
	Attribute: loyalty to human beings
	
	Behavior: housekeeping
	}
	
	
	class cat extend animal{
	Attribute: supercilious
	
	Behavior: catching mice
	}

Our newly defined dog is inherited from animals, so dogs also belong to animals. They also have animal attributes, hair and animal behavior, eating and sleeping. At the same time, they also have characteristics that other animals do not have - loyalty to their masters and the ability to look after their homes. Similarly, cats inherit from animals, so we understand the relationship of inheritance through animal relations.

  • 3. Polymorphism
    The properties and behaviors inherited from the parent class of a subclass have different manifestations on different subclasses. This different manifestation is called polymorphism. Take the above cats and dogs for example. Both cats and dogs inherit from animals. They can eat and have the behavior of eating. However, cats and dogs eat different things. Cats like to eat fish while dogs like to eat bones. For the different manifestations of the same behavior under different subclasses, we call it polymorphism. Of course, under the same category, the different manifestations of different examples are also called polymorphism. For example, my dog likes to eat bones, and Xiaoming's dog likes to eat meat buns.

Cliche - classes and objects

Why do we say this is an old saying, because most of our programming is to encapsulate a new class and instantiate a new object. To understand the difference between classes and objects, we must first understand the meaning of "instantiation". Instantiation usually refers to obtaining instances in the class according to the encapsulated class, such as creating a new instance, or sometimes obtaining them from other places. These two points are very important. In our collaborative work, many instances are not created by ourselves. We need to get the instances created by others to complete the corresponding operations (such as server request instance request and response instance response, which we often use later). Therefore, class is an abstract group category with common attributes, such as the dog we created. The object is a specific instance of the category, such as the dog I own and the dog Zhang San owns.

nodejs class

In the early days, we often created classes by prototyping, such as the following code

function Animal(hairColor) {
    this.hairColor = hairColor;
}

Animal.prototype.eat = function () {
    console.log('I'm having dinner')
};

var animal = new Animal('black');
animal.eat() // Print "I'm having dinner"

But now it's 2021, and the keyword class of the class has been clearly defined in the es6 specification. Let's use the new es6 specification to create the class and instantiate the object of our class today.

We want to order an animal, a cat and a dog. Then create a cat and a dog, let them introduce themselves respectively, and complete the behavior of eating and sleeping.

code implementation

class Animal {
    constructor(name, hairColor) {  // When creating the animal instance, you need the name and hair color attributes
        this.name = name; // Name and nickname attribute. this represents the instance itself
        this.hairColor = hairColor; // Fur attributes
    }

    eat() { // Eating behavior
        console.log(`My name is ${this.name},I'm having dinner`)
    }

    sleep() { // Sleeping behavior
        console.log(`My name is ${this.name},I'm sleeping`)
    }
}

class Dog extends Animal {
    constructor(name, hairColor, masterName) { //The owner name is required when creating a dog
        super(name, hairColor)
        this.masterName = masterName
    }

    eat(food) {
        console.log(`I am ${this.masterName}Home dog:`)
        super.eat() // Observe the eating behavior of the parent animal
        console.log(`I'm eating. ${food}`)
    }


    protectHome() {

        console.log('I'm looking after the house')
    }
}


class Cat extends Animal {
    constructor(name, hairColor, masterName) { //The owner name is required when creating a dog
        super(name, hairColor)
        this.masterName = masterName
    }

    eat(food) {
        console.log(`I am ${this.masterName}Cat at home:`)
        super.eat()// Observe the eating behavior of the parent animal
        console.log(`I'm eating. ${food}`)
    }

    catchMouse() {
        console.log('I'll catch the mouse')
    }
}


const xiaomingsCat = new Cat('Tinkle bell', 'black', 'Xiao Ming') //Create kitten instance
xiaomingsCat.eat('Dried fish') // The kitten went to eat
xiaomingsCat.catchMouse() //The kitten went to catch the mouse

const xiaohongsDog = new Dog('peas', 'grey', 'Xiao Hong') // Create dog instance
xiaohongsDog.eat('steamed meat bun') // The dog went to eat
xiaohongsDog.protectHome() //The dog went to watch the house

Operation results

Keyword description

extends keyword

ES6 provides the extends keyword to implement class inheritance. The usage is class A extends B, indicating that A inherits from B

[external chain picture transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-ky123mpr-1624675880369)( file:///Users/tristan/.config/joplin-desktop/resources/7d21e5a0c0ec4026aec45f0224fc5b07.png )]

super keyword

Super represents the parent class object and the constructor of the child class. The super method in the constructor implements the call to the constructor of the parent class. Use super The eat () method implements the eat method call to the parent class instance object. You should pay attention to the following points when calling:

  • 1. The super method must be called in the subclass constructor, otherwise an error will be reported in the new object.

  • 2, the subclass constructor must call super before using this, otherwise it will be wrong.

  • 3. When a subclass inherits from the parent class, if it needs to abide by the behavior of the parent class, it needs to pass super XXX () to call the parent class behavior.

last

Through this chapter, we should master what is object-oriented, the difference between classes and objects, how to define classes in nodejs, and how to instantiate an object. Everything is difficult at the beginning. Understanding object-oriented can't be learned in these hundreds of words. We need to sublimate our understanding of it in use.
Also, object-oriented is not higher than process oriented, it is only applied in different scenarios. Simple atomization is more suitable to be solved by process oriented thinking, and object-oriented is more like a classified management of multiple process oriented.

Keywords: node.js Programming OOP

Added by unlishema.wolf on Mon, 24 Jan 2022 05:32:51 +0200