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

CSS stacking and z-index example code

Cascading and Cascading Levels HTML elements are ...

Solution to Tomcat server failing to open tomcat7w.exe

I encountered a little problem when configuring t...

A brief discussion on the use of Web Storage API

Table of contents 1. Browser local storage techno...

Talk about implicit conversion in MySQL

In the course of work, you will encounter many ca...

Detailed explanation of three ways to connect Docker containers to each other

There are three ways to interconnect and communic...

Detailed explanation of real-time backup knowledge points of MySQL database

Preface The need for real-time database backup is...

Detailed explanation of Apache SkyWalking alarm configuration guide

Apache SkyWalking Apache SkyWalking is an applica...

Linux ssh server configuration code example

Use the following terminal command to install the...

Ten Experiences in Web Design in 2008

<br />The Internet is constantly changing, a...

A brief understanding of MySQL SELECT execution order

The complete syntax of the SELECT statement is: (...

Simple analysis of EffectList in React

Table of contents EffectList Collection EffectLis...

Summary of event handling in Vue.js front-end framework

1. v-on event monitoring To listen to DOM events,...

Process parsing of reserved word instructions in Dockerfile

Table of contents 1. What is Dockerfile? 2. Analy...