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

js to realize the mouse following game

This article shares the specific code of js to im...

How to install MySQL 8.0.13 in Alibaba Cloud CentOS 7

1. Download the MySQL installation package (there...

How to install Graphviz and get started tutorial under Windows

Download and installConfigure environment variabl...

Beginners learn some HTML tags (3)

Beginners who are exposed to HTML learn some HTML...

MySQL 8.0.18 installation and configuration method graphic tutorial

This article records the installation and configu...

Solve the cross-domain problem of get and post requests of vue $http

Vue $http get and post request cross-domain probl...

How to use css overflow: hidden (overflow hiding and clearing floats)

Overflow Hide It means hiding text or image infor...

In-depth analysis of MySQL database transactions and locks

Table of contents 1. Basic Concepts ACID 3.AutoCo...

Installation tutorial of mysql 5.7 under CentOS 7

1. Download and install the official MySQL Yum Re...

MySQL uses inet_aton and inet_ntoa to process IP address data

This article will introduce how to save IP addres...

Sample code for implementing rolling updates of services using Docker Swarm

1. What is Docker Swarm? Docker Swarm is a cluste...

XHTML language default CSS style

html,address, blockquote, body,dd,div, dl,dt,fiel...

4 functions implemented by the transform attribute in CSS3

In CSS3, the transform function can be used to im...

JavaScript data transmission between different pages (URL parameter acquisition)

On web pages, we often encounter this situation: ...