Detailed explanation of 6 ways of js inheritance

Detailed explanation of 6 ways of js inheritance

Prototype chain inheritance

Prototype inheritance is the main inheritance method in ECMAScript. The basic idea is to inherit the properties and methods of multiple reference types through prototypes. What is a prototype chain? Each constructor has a prototype object. The instance created by calling the constructor has a pointer __proto__ pointing to the prototype object. This prototype may be an instance of another type, so there may also be a pointer pointing to another prototype inside, and thus a prototype chain is formed.

Code:
function SuperType() {
	this.property = true;
}
SuperType.prototype.getSuperValue = function() {
	return this.property;
};
function SubType() {
	this.subproperty = false;
}
// Inherit SuperType
SubType.prototype = new SuperType();
SubType.prototype.getSubValue = function () { //Note that you cannot add new methods through object literals, otherwise the previous line will be invalid return this.subproperty; 
};
let instance = new SubType();
console.log(instance.getSuperValue()); // true

shortcoming

1. If the attribute of the parent class instance is a reference type, the instance attribute of the parent class will become the prototype attribute of the subclass. All instances created by the subclass will share these methods. If the attribute of one instance is modified, the attributes of other instances will also be modified.

2. Subtypes cannot pass parameters to the parent type's constructor when instantiating

Constructor inheritance

In order to solve the inheritance problem caused by prototypes containing reference values, a technique called "stealing constructors" became popular, also known as "object masquerade" or "classical inheritance". The idea is to use the constructor in the subclass.

The parent class constructor is called in the number. You can use the call() and apply() methods to execute functions with the newly created object as the context.

function SuperType(name) {
 this.colors = ["red","blue","green"];
 this.name = name;
 }
function SubType(name) {
 SuperType.call(this,name);
}
let instance1 = new SuperType('Xiaoming')
let instance2 = new SuperType('小白')
instance1.colors .push('yellow')
console.log(instance1) //{name:"Xiao Ming",colors:["red","blue","green","yellow"]...}
console.log(instance2) //{name:"Xiaobai",colors:["red","blue","green"]...}

//Can pass parameters and fix reference issues. Can inherit multiple constructor properties (call multiple)

shortcoming:

1. Methods can only be called in the constructor. Functions cannot be reused. That is, each time a subclass generates an instance, attributes and methods are generated once.
2. Subclasses cannot access methods on parent class prototypes

Composition inheritance

It combines the prototype chain and the constructor, bringing together the advantages of both. The basic idea is to use the prototype chain to inherit the properties and methods on the prototype, and inherit the instance properties through the constructor. This allows methods to be defined on the prototype for reuse, while also allowing each instance to have its own properties.

function SuperType(name){
	this.name = name;
	this.colors = ["red","blue","green"];
}
SuperType.prototype.sayName = function() {
	console.log(this.name);
};
function SubType(name, age){
	// Inherited properties Second call SuperType.call(this, name);
	this.age = age;
}
// The first call of the inherited method SubType.prototype = new SuperType();
SubType.prototype.sayAge = function() {
	console.log(this.age);
};
let instance1 = new SubType("Nicholas", 29);
instance1.colors.push("black");
console.log(instance1.colors); //["red,blue,green,black"]
instance1.sayName(); // "Nicholas";
instance1.sayAge(); // 29
let instance2 = new SubType("Greg", 27);
console.log(instance2.colors); // ["red,blue,green"]
instance2.sayName(); // "Greg";
instance2.sayAge(); // 27

//Can inherit the properties of the parent class prototype, can pass parameters, and can be reused. Constructor properties introduced by each new instance are private

shortcoming

Calling the parent class constructor twice consumes more memory

Prototypal inheritance

Even without defining custom types, you can share information between objects through prototypes.

function object(person) {
 function F() {}
 F.prototype = person
 return new F()
}

let person = {
 name:'Xiaoming',
 colors:['red','blue']
}

let person1 = object(person)
person1.colors.push('green')
let person2 = object(person)
person1.colors.push('yellow')
console.log(person) //['red','blue','green','yellow']

Applicable environment: You have an object and want to create a new object based on it. You need to pass this object to object() first, and then modify the returned object appropriately. Similar to Object.create() when only the first parameter is passed, it essentially makes a shallow copy of the passed object. The disadvantage is that the properties of the new instance are added later and cannot be reused.

Parasitic inheritance

A type of inheritance that is closer to prototypal inheritance is parasitic inheritance, which is similar to parasitic constructors and factory patterns: create a function that implements inheritance, enhance the object in some way, and then return the object.

function object(person) {
 function F() {}
 F.prototype = person
 return new F()
}
function createAnother(original){
	let clone = object(original); // Create a new object by calling a function clone.sayHi = function() { // Enhance this object in some way console.log("hi");
};
	return clone; // return this object}

Parasitic inheritance is also suitable for scenarios where you are mainly concerned with objects and do not care about types and constructors.
Disadvantages: Adding functions to objects through parasitic inheritance makes functions difficult to reuse, similar to the constructor pattern

Parasitic Compositional Inheritance

The most commonly used inheritance method is also the best. Combined inheritance will call the parent class constructor twice, which has efficiency issues. In fact, the essence of the subclass prototype is to contain all the instance properties of the parent class object. The subclass constructor only needs to rewrite its own prototype during execution. The basic idea is not to assign values ​​to the subclass prototype by calling the parent class constructor, but to obtain a copy of the parent class prototype. In the final analysis, it is to use parasitic inheritance to inherit the parent class prototype, and then assign the returned new object to the child class prototype.

//Core code function object(person) {
 function F(params) {}
 F.prototype = person
 return new F()
}
function inheritPrototype(SubType,SuperType) {
 let prototype = object(SuperType.prototype) //Generate a copy of the parent class prototype //Override the constructor of this instance
 prototype.constructor = SubType

 //Assign this object copy to the prototype of the subclass SubType.prototype = prototype
}

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;
}

//Call the inheritPrototype function to assign the subclass prototype value, fixing the problem of combined inheritance inheritPrototype(SubType, SuperType);

SubType.prototype.sayAge = function() {
	console.log(this.age);
};

Summarize

This concludes this article about 6 ways of js inheritance. For more relevant js inheritance content, please search 123WORDPRESS.COM’s previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Understanding JavaScript inheritance in one article
  • Summary of 6 common inheritance methods in js
  • 6 inheritance methods of JS advanced ES6
  • Six inheritance methods in JS and their advantages and disadvantages
  • Detailed explanation of native Javascript inheritance methods and their advantages and disadvantages
  • Several ways to implement inheritance in JavaScript
  • 6 JavaScript inheritance methods and their advantages and disadvantages (summary)
  • Examples of several common ways to implement inheritance in JS
  • Share several inheritance methods in JavaScript

<<:  Solution to forgetting the root password of self-built MySQL in Alibaba Cloud Linux CentOS 7.2

>>:  Shell script nginx automation script

Recommend

A brief analysis of the usage of USING and HAVING in MySQL

This article uses examples to illustrate the usag...

Solve the problem of IDEA configuring tomcat startup error

The following two errors were encountered when co...

A brief introduction to the simple use of CentOS7 firewall and open ports

Overview (official has more detailed description)...

MySQL optimization tutorial: large paging query

Table of contents background LIMIT Optimization O...

How to solve the margin collapse problem in CSS

First, let's look at three situations where m...

Detailed explanation of the usage of grep command in Linux

1. Official Introduction grep is a commonly used ...

How to set the style of ordered and unordered list items in CSS

In an unordered list ul>li, the symbol of an u...

How to use Nginx to carry rtmp live server

This time we set up an rtmp live broadcast server...

Example of how to configure nginx in centos server

Download the secure terminal MobaXterm_Personal F...

React implements a highly adaptive virtual list

Table of contents Before transformation: After tr...

MySQL statement arrangement and summary introduction

SQL (Structured Query Language) statement, that i...

jQuery implements the drop-down box for selecting the place of residence

The specific code for using jQuery to implement t...

Sublime Text - Recommended method for setting browser shortcut keys

It is common to view code effects in different br...

Steps to create a Vite project

Table of contents Preface What does yarn create d...