Three methods of inheritance in JavaScript

Three methods of inheritance in JavaScript

inherit

1. What is inheritance

Inheritance: First of all, inheritance is a relationship, the relationship between classes. There are no classes in JS, but classes can be simulated through constructors, and then inheritance can be achieved through prototypes.

  • Inheritance is also for data sharing, and inheritance in js is also for data sharing

We can think of the prototype, and its two functions are:

  • Prototype function 1: data sharing, saving memory space
  • The second role of prototype: to achieve inheritance

Inheritance is a relationship: the relationship between the parent class level and the class level

example:

Person categories: name, gender, age, eating, sleeping

Student categories: name, gender, age, eating, sleeping, and studying behaviors

Teacher category: name, gender, age, meals, sleep, salary, teaching behavior

Programmer: Name, Gender, Age, Eating, Sleeping, Salary, Writing Code

Driver category: name, gender, age, meals, sleep, salary, driving

Animal categories: weight, color, eating

Dog categories: weight, color, eating, biting

Erha category: weight, color, eating, biting to make the owner happy, woof woof, you are so handsome

Object-oriented features: encapsulation, inheritance, polymorphism

Encapsulation: It is to wrap a value and store it in a variable - to wrap a bunch of repeated code in a function - to wrap a series of attributes in an object - to wrap some functions (methods) with similar functions in an object - to wrap many similar objects in a js file - Encapsulation

Polymorphism: An object has different behaviors, or the same behavior produces different results for different objects. To have polymorphism, you must first have inheritance. Polymorphism can be simulated in JS, but it will not be used or simulated.

2. Three methods of JavaScript inheritance

Constructor property inheritance: borrowing constructors

When inheriting, you don't need to change the prototype's pointer, you can just call the parent's constructor to assign values ​​to the properties.

—— Borrowing constructor: Take the constructor of the parent to be inherited and use it.

Borrowing constructor:

Constructor name.call(current object, attribute, attribute, attribute...);

Advantages: Solve the problem of attribute inheritance and non-duplicate values

Defect: Methods in parent classes cannot be inherited

function Person (name, age) {
  this.type = 'human'
  this.name = name
  this.age = age
}

function Student (name, age) {
  // Borrow the constructor to inherit the attribute member Person.call(this, name, age)
}

var s1 = Student('张三', 18)
console.log(s1.type, s1.name, s1.age) // => human Zhang San 18

Examples:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>title</title>
  <script>
    function Person(name, age, sex, weight) {
      this.name = name;
      this.age = age;
      this.sex = sex;
      this.weight = weight;
    }
    Person.prototype.sayHi = function () {
      console.log("Hello");
    };
    function Student(name,age,sex,weight,score) {
      //Borrow the constructor Person.call(this,name,age,sex,weight);
      this.score = score;
    }
    var stu1 = new Student("Xiaoming",10,"male","10kg","100");
    console.log(stu1.name, stu1.age, stu1.sex, stu1.weight, stu1.score);

    var stu2 = new Student("Xiaohong",20,"Female","20kg","120");
    console.log(stu2.name, stu2.age, stu2.sex, stu2.weight, stu2.score);

    var stu3 = new Student("Xiao Li",30,"Yao","30kg","130");
    console.log(stu3.name, stu3.age, stu3.sex, stu3.weight, stu3.score);


  </script>
</head>
<body>


</body>
</html>

Prototype method inheritance of constructors: copy inheritance (for-in)

Copy inheritance; copy the properties or methods of one object directly to another object

function Person (name, age) {
  this.type = 'human'
  this.name = name
  this.age = age
}

Person.prototype.sayName = function () {
  console.log('hello ' + this.name)
}

function Student (name, age) {
  Person.call(this, name, age)
}

// The prototype object copies and inherits the prototype object members for(var key in Person.prototype) {
  Student.prototype[key] = Person.prototype[key]
}

var s1 = Student('张三', 18)

s1.sayName() // => hello Zhang San

Examples:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>title</title>
  <script>

    //Copy inheritance; copy the properties or methods of an object directly to another object function Person() {
    }
    Person.prototype.age=10;
    Person.prototype.sex="Male";
    Person.prototype.height=100;
    Person.prototype.play = function () {
      console.log("having fun");
    };
    var obj2={};
    //Person has a prototype in its construction. Prototype is an object. In it, age, sex, height, and play are all properties or methods of the object. for(var key in Person.prototype){
      obj2[key]=Person.prototype[key];
    }
    console.dir(obj2);
    obj2.play();



  </script>
</head>
<body>


</body>
</html>

Another way of inheritance: prototype inheritance

Prototype inheritance: changing the prototype's direction

function Person (name, age) {
  this.type = 'human'
  this.name = name
  this.age = age
}

Person.prototype.sayName = function () {
  console.log('hello ' + this.name)
}

function Student (name, age) {
  Person.call(this, name, age)
}

//Use the characteristics of prototype to achieve inheritance Student.prototype = new Person()

var s1 = Student('张三', 18)

console.log(s1.type) // => human

s1.sayName() // => hello Zhang San

Combination inheritance: prototype + borrowed constructor inheritance

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>title</title>
  <script>


    //Prototype inheritance //Borrowing constructor to implement inheritance //Combined inheritance: prototype inheritance + borrowing constructor inheritance function Person(name, age, sex) {
      this.name=name;
      this.age=age;
      this.sex=sex;
    }
    Person.prototype.sayHi = function () {
      console.log("Sawadee Ka");
    };
    function Student(name,age,sex,score) {
      //Borrowing constructor: Problem of duplicate attribute values ​​Person.call(this,name,age,sex);
      this.score=score;
    }
    //Change the prototype pointing to ---- inheritance Student.prototype = new Person(); //Do not pass the value Student.prototype.eat = function () {
      console.log("eat");
    };
    var stu=new Student("小黑",20,"男","100分");
    console.log(stu.name,stu.age,stu.sex,stu.score);
    stu.sayHi();
    stu.eat();
    var stu2=new Student("小黑黑",200,"男人","1010分");
    console.log(stu2.name,stu2.age,stu2.sex,stu2.score);
    stu2.sayHi();
    stu2.eat();

    //Both properties and methods are inherited</script>
</head>
<body>


</body>
</html>

Inheritance Summary

Prototype inheritance: changing the prototype's direction

Borrowing constructor inheritance: mainly solves the problem of attributes

Combined inheritance: prototype inheritance + borrowed constructor inheritance

It can solve both attribute problems and method problems

Copy inheritance: It is to copy the attributes or methods that need to be shared in an object to another object by directly traversing them.

Summarize

This concludes this article about the three methods of JavaScript inheritance. For more information about JavaScript inheritance methods, please search previous articles on 123WORDPRESS.COM or continue browsing the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Detailed explanation of native Javascript inheritance methods and their advantages and disadvantages
  • Diving into JS inheritance
  • Detailed explanation of 6 ways of js inheritance
  • Several ways to implement inheritance in JavaScript
  • Five ways to implement inheritance in js
  • Examples of several inheritance methods in JavaScript
  • Detailed explanation of JavaScript inheritance
  • JavaScript object-oriented class inheritance case explanation

<<:  MySQL database operation and maintenance data recovery method

>>:  Detailed explanation of the installation and use of Linux scheduled tasks crontabs

Recommend

A complete list of commonly used MySQL functions (classified and summarized)

1. Mathematical Functions ABS(x) returns the abso...

CSS3 mobile vw+rem method to achieve responsive layout without relying on JS

1. Introduction (1) Introduction to vw/vh Before ...

Float and Clear Float in Overview Page

1. Float: The main purpose is to achieve the effe...

The benefits and examples of placing the site map at the bottom of the web page

In the past, almost every website had a sitemap p...

JS uses clip-path to implement dynamic area clipping function

background Today, I was browsing CodePen and saw ...

Two ways to implement HTML page click download file

1. Use the <a> tag to complete <a href=&...

CSS3 realizes particle animation effect when matching kings

When coding, you will find that many things have ...

A brief discussion on the issue of element dragging and sorting in table

Recently, when using element table, I often encou...

Summary of the pitfalls of using primary keys and rowids in MySQL

Preface We may have heard of the concept of rowid...

Detailed explanation of the correct use of the count function in MySQL

1. Description In MySQL, when we need to get the ...

Solve the problem of Docker starting Elasticsearch7.x and reporting an error

Using the Docker run command docker run -d -p 920...

JavaScript to achieve product magnifying glass effect

This article shares the specific code of JavaScri...