A brief talk about JavaScript parasitic composition inheritance

A brief talk about JavaScript parasitic composition inheritance

Composition inheritance

Combination inheritance is also called pseudo-classical inheritance. It combines the prototype chain and constructor theft that we talked about yesterday, combining the advantages of both. Its basic idea is to use the prototype chain to inherit the properties and methods on the prototype, and to inherit the instance properties by stealing the constructor. The advantage of this is that the methods defined on the prototype can be reused, and each instance has its own properties.

    function SuperType (name) {
        this.name = name;
        this.colors = ["red","yellow","bule"];
    }
    SuperType.prototype.sayName = function(){
        console.log(this.name)
    }
    function SubType(name,age){
        SuperType.call(this,name);
        this.age = age;
    }
    SubType.prototype = new SuperType();
    SubType.prototype.sayAge = function(){
        console.log(this.age);
    }
    let instancel = new SubType("jackson",22);
    instancel.colors.push("pink");
    instancel.sayName(); // "jackson"
    instancel.sayAge(); //22
    console.log(instancel.colors); // ["red", "yellow", "bule", "pink"]
    
    let instance2 = new SubType("bear", 20);
    console.log(instance2.colors); // ["red", "yellow", "bule"]
    instance2.sayName(); // "bear";
    instance2.sayAge(); // 20

Does the above code make you feel suddenly enlightened? SubType calls SuperType and passes in name, then defines its own property age. In addition, SubType.prototype is also assigned to the SuperType instance. After the prototype is assigned, the sayage method is added to this prototype, thus creating two subType instances. These two instances have their own properties and can share the same methods.

Combination inheritance makes up for the shortcomings of prototype chain and stolen constructor, and is the most used inheritance mode in js.

Parasitic inheritance

Parasitic inheritance is to wrap an object with a function and then return the call of this function. This function becomes an instance or object that can add properties at will. This is the principle of object.create().

  // Parasitic inheritance function subobject(obj) {
        let clone = Object(obj);
        clone.sayName = function(){
            console.log("jackson")
        };
        return clone;
    }
    let sub = {
        name:"bear"
    }
    let sup = subobject(sub);
    sup.sayName();//jackson

This example returns a new object based on the sub object. The returned sup object has the properties and methods of sub, and a new method sayName().

Parasitic inheritance is also suitable for scenarios where you are mainly concerned with objects and do not care about types and constructors. The object() function is not required for parasitic inheritance; any function that returns a new object can be used here.

Note that adding functions to objects through parasitic inheritance can make functions difficult to reuse, similar to the Constructor pattern.

Parasitic Compositional Inheritance

There are certain efficiency issues with composite inheritance. Its parent class constructor will always be called twice, once when creating the subclass prototype and once in the subclass constructor. Essentially, subclasses only need to rewrite their own prototypes at execution time.

     function inheritPrototype(subType, superType) {
        let prototype = Object(superType.prototype); // Create object prototype.constructor = subType; // Enhanced object subType.prototype = prototype; // Assign object }

This inheritPrototype() function implements the core logic of parasitic composition inheritance. This function receives two parameters: the subclass constructor and the parent class constructor. Inside this function, the first step is to create a copy of the parent class prototype. Then, set the constructor property for the returned prototype object to solve the problem of losing the default constructor due to overriding the prototype. Finally, the newly created object is assigned to the prototype of the subtype. As shown in the following example, calling inheritPrototype() can implement the subtype prototype assignment in the previous example:

function SuperType(name) {
        this.name = name;
        this.colors = ["red", "blue", "green"];
    }
    SuperType.prototype.sayName = function () {
        console.log(this.name);
    };

    function SubType(name, age) {
        SuperType.call(this, name);
        this.age = age;
    }
    inheritPrototype(SubType, SuperType);
    SubType.prototype.sayAge = function () {
        console.log(this.age);
    };

Here, the SuperType constructor is called only once, avoiding unnecessary and unused properties on SubType.prototype, so it can be said that this example is more efficient. And the prototype chain still remains intact.

Summarize

This is the end of this article about JavaScript parasitic composition inheritance. For more relevant JS parasitic composition inheritance content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Javascript combination inheritance method code example analysis
  • Examples of various combinations of inheritance in JavaScript
  • Analysis of the principle and usage of JavaScript parasitic combination inheritance
  • Summary of inheritance methods of JavaScript classes [combination inheritance analysis]
  • Detailed explanation of JavaScript parasitic combined inheritance examples
  • [The Road to JS Masters] Detailed Explanation of the Generation of Graphical Inheritance from Prototype Chain to Combination Inheritance
  • [JS Master Road] Detailed explanation of the advantages of parasitic combination inheritance
  • Common inheritance in js - combined inheritance
  • JS inheritance: borrowed constructor inheritance and combined inheritance
  • JavaScript Composition and Inheritance Explained

<<:  The handler PageHandlerFactory-Integrated has a bad module ManagedPipelineHandler in its module list

>>:  Summary of methods for cleaning Mysql general_log

Recommend

Mysql practical exercises simple library management system

Table of contents 1. Sorting function 2. Prepare ...

MySQL 8.0.17 installation and configuration method graphic tutorial

This article shares the installation and configur...

How to use nginx to build a static resource server

Taking Windows as an example, Linux is actually t...

jQuery manipulates cookies

Copy code The code is as follows: jQuery.cookie =...

Using nginx + fastcgi to implement image recognition server

background A specific device is used to perform i...

MySQL 8.0.12 Simple Installation Tutorial

This article shares the installation tutorial of ...

How to keep running after exiting Docker container

Phenomenon: Run an image, for example, ubuntu14.0...

MySQL Server 8.0.13.0 Installation Tutorial with Pictures and Text

Install 8.0.13 based on MySQL 6.1.3. MySQL 8.0.13...

Analysis of the process of simply deploying nginx in Docker container

1. Deploy nginx service in container The centos:7...

Nginx configuration SSL and WSS steps introduction

Table of contents Preface 1. Nginx installation 1...

Analysis of Difficulties in Hot Standby of MySQL Database

I have previously introduced to you the configura...

Example of how to set up a third-level domain name in nginx

Problem Description By configuring nginx, you can...

Practice of deploying web applications written in Python with Docker

Table of contents 1. Install Docker 2. Write code...