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

Experience in solving tomcat memory overflow problem

Some time ago, I submitted a product version to t...

SASS Style Programming Guide for CSS

As more and more developers use SASS, we need to ...

Detailed explanation of template tag usage (including summary of usage in Vue)

Table of contents 1. Template tag in HTML5 2. Pro...

The problem of form elements and prompt text not being aligned

Recent projects involve the creation of a lot of ...

Understanding MySQL clustered indexes and how clustered indexes grow

In this note, we briefly describe What is the B+T...

The process of quickly converting mysql left join to inner join

During the daily optimization process, I found a ...

Detailed explanation of the usage of 5 different values ​​of CSS position

The position property The position property speci...

MySQL 5.6 zip package installation tutorial detailed

Previously, we all used files with the suffix .ms...

Example code for implementing an Upload component using Vue3

Table of contents General upload component develo...

Understand the principles and applications of JSONP in one article

Table of contents What is JSONP JSONP Principle J...

Detailed explanation of lazy loading and preloading of webpack

Table of contents Normal loading Lazy Loading Pre...

Docker deploys Macvlan to achieve cross-host network communication

Basic concepts: Macvlan working principle: Macvla...

HTML table tag tutorial (19): row tag

The attributes of the <TR> tag are used to ...

JavaScript Objects (details)

Table of contents JavaScript Objects 1. Definitio...

Use semantic tags to write your HTML compatible with IE6,7,8

HTML5 adds more semantic tags, such as header, fo...