Detailed explanation of Js class construction and inheritance cases

Detailed explanation of Js class construction and inheritance cases

The definition and inheritance of classes in JS are really varied, so I’ll open a separate notebook to record them.

definition

Methods derived from Object

1.new Object: dynamically define properties and methods after creating an object var Car = new Object;
Car.color = "red";
Car.showColor = function(){
	console.log(this.color);
}
//If you want to inherit, you must first construct an empty object and then use the __proto__ prototype chain to inherit var Car1 = new Object; //or = {}
Car1.__proto__ = Car;

Using function constructs

1. Factory function: Generate a class within a function. The advantage is that you don't need to construct an empty object + inherit the prototype chain, and directly return a copy of the object, similar to the constructor function createCar(){ //You can also pass the parameter creatCar(color) to this function
	let car = new Object;
	car.color = "red"; // Pass parameter: car.color = color
	car.showColor = function(){
		console.log(this.color);
	}
	return car;
}

var newCar = createCar(); // Pass parameters: createCar("red")
//However, if you use the factory function, you will construct the showColor method every time you construct a function, which is not cost-effective. //So you can define a method for inheritance for all classes before the factory function of the class. function showColor(){
	console.log(this.color);
}
function createCar(){
...
	car.showColor = showColor;
...
}

2. Constructor method: Similar to the factory function method, use the constructor method. The difference is that the attribute in the constructor can only be this.attr
function Car(color,num){
	this.color = color;
	this.num = num;
	this.showColor = function(){
		console.log(this.color);
	}
	this.drivers = new Array("mike");
}
var car1 = new Car("red",1); //Note that the properties and methods of Car itself cannot be accessed at this time. They can only be accessed after instantiation. //For example: console.log(new Car("red",1).color)
					 //This means that the constructor is really a class-like constructor rather than an instantiated object, and js also //has objects in the traditional sense rather than just function objects. //Same as method 1, the showColor function in the Car class will be constructed every time it is constructed, occupying unnecessary space var car2 = new Car("green",1);
car1.drivers.push("kiki");
console.log(car2.drivers); //There is no phenomenon of referencing the same array 3. Prototype method: Similar to Object derivation, forming a prototype chain based on Object, and then binding methods and properties function Car(){};
Car.prototype.color = "red";
Car.prototype.showColor = function(){
		console.log(this.color);
}
//Car.prototyoe = { //Put multiple bound functions into an anonymous class to write // mathod1:function(){...};
// mathod2:function(){...};
//}
Car.prototype.drivers = new Array("mike","jhon");
var car1 = new Car(); //You must create an instance to call methods to access properties var car2 = new Car();
car1.drivers.push("bill");
console.log(car1.color);
console.log(car2.drivers);
//In this way, all the attributes of bound arry point to the same array object and are references. When you change the color of one instance, all colors change together.

Hybrid Approach:

1. Constructor + prototype: The constructor only constructs properties and in-class arrays, and uses the prototype to declare in-class functions function Car(color){
	this.color = color;
	this.drivers = new Array("mike");
}
Car.prototype.showColor = function(){
	console.log(this.color);
}
var car1 = new Car(); //You must create an instance to call methods to access properties var car2 = new Car();
car1.drivers.push("bill");
console.log(car2.drivers); //Avoids the disadvantage of the prototype method 2. Use the class keyword to define a class: you cannot define properties directly outside the class, and you still need to use the prototype method to bind function objects outside the class.
class Car{
           constructor(color) {
                this.color = color;
           }
           drivers = new Array("mike","jhon");
           hello = function(){
           		return "Di Di"+ this.color; 
           }
           
        }

Car.prototype.hello = function (){ //outside class binding method return "Di Di";
}

var car1 = new Car("red");
var car2 = new Car("green");
car1.drivers.push("kiki");
console.log(car1.color);
console.log(car2.hello());

In summary, when variables are defined within a class, the constructor will be called when the instance is constructed, while the methods and properties bound outside the class will be in the form of reference and will not participate in the construction and will be called directly. At the same time, it is also convenient for keeping confidentiality and hiding information.

inherit

1. Pretend inheritance: Inherit the class as the constructor of the new class. It's a bit magical. In js, the class can be regarded as a strange property of the function object. function Car1(color){
	this.color = color;
	this.showColor = function(){
		console.log("this car is "+this.color);
	}
	this.drivers = new Array("mike");
}

function Car2(){
	this.makeSound = function(){
		console.log("Di Di");
	}
}

function Car3(color){
	this.newConstruct = Car1; //Pass in as a constructor this.newConstruct(color); //Call the constructor delete this.newConstruct;
	this.newConstruct2 = Car2; //Multiple inheritance, but due to the closure mechanism, different constructor names must be used this.newConstruct2(); 
	delete this.newConstruct2;
}//Similarly, fake inheritance can also use .prototype to bind the constructor var car1 = new Car3("red");
var car2 = new Car3("green");
car1.drivers.push("kiki");
console.log(car1.color);
car1.showColor();
car1.makeSound();
console.log(car2.drivers);

2. Use the parent class method call and apply to inherit function Car1(color){
	this.color = color;
	this.showColor = function(){
		console.log("this car is"+this.color);
	}
}
function Car2(num){
	this.num = num;
	this.makeSound = function(){
		console.log("Di Di");
	}
}

function Car3(color,num){
	Car1.call(this, color);
	Car2.apply(this, augments); //augments is an array containing the required parameters}

var car1 = new Car3("red",1);
var car2 = new Car3("green",2);
console.log(car1.color);
console.log(car2.num);
car1.showColor();
car1.makeSound();

//You can also write .apply and .call outside the class, but they can only operate on instances and cannot be used to construct classes. 3. Use prototype chain for inheritance: Use __proto__ and .prototype to construct a prototype chain. The disadvantage is that multiple inheritance cannot be achieved. Multiple inheritance can only be achieved by binding it into a constructor or creating several classes to inherit in a chained manner. function Car1(color){
	this.color = color;
	this.showColor = function(){
		console.log("this car is"+this.color);
	}
}
function Car3(){};
Car3.prototype = new Car1();

4. Using class...extends..., you can also implement inheritance, but you cannot implement multiple inheritance. You can only implement multiple inheritance by using multiple classes as nodes like the prototype chain. This is a feature of ES6. ES6 also introduced the let, public, private, and protected keywords, but it cannot implement multiple inheritance, and there is no concept of packages, which is also quite strange. class Car2 extends Car1{
           constructor(color) {
                super(); //Similar to java, super itself can represent the parent class. Here, it is used to represent the parent class. //Constructor this.color = color;
           }
           drivers = new Array("mike","jhon");
           hello = function(){
           		return "Di Di"+ this.color; 
           }  
        }

5. Use the variable parameter encapsulation function extend (need to be implemented by yourself) to implement the chain inheritance of multiple classes in sequence extend(A,B,C), B node inherits A, C inherits B (actually it is still a chain method, but it is encapsulated for easy understanding. This is the answer from Zhihu boss Xiaohong and csdn boss Yuben, https://blog.csdn.net/sysuzhyupeng/article/details/54846949 The Zhihu way of writing is not easy to understand). The main thing is to use the characteristics of classes as functions and as return values

So, under normal circumstances: create a class using class or constructor + prototype; inherit a class using class...extends... or call method. Learn about factory methods and inheritance in disguise.

I won’t go into detail about overloading, as it is as imperfect as class, and you can only implement it yourself using augmentations.length.

This is the end of this article about the construction and inheritance cases of Js classes. For more content about the construction and inheritance of Js classes, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • JavaScript class inheritance multiple implementation methods
  • Inheritance definition and usage analysis of js class
  • 15 minutes to gain in-depth understanding of JS inheritance classification, principles and usage
  • How much do you know about JavaScript's constructor, prototype, prototype chain and new?
  • JS Easy to understand Function and Constructor
  • JavaScript knowledge: Constructors are also functions
  • Detailed explanation of classes, inheritance, and constructors in javascript

<<:  MySQL 8.0.21 installation tutorial under Windows system (illustration and text)

>>:  Take you to understand the event scheduler EVENT in MySQL

Recommend

Detailed explanation of common template commands in docker-compose.yml files

Note: When writing the docker-compose.yml file, a...

Detailed steps for installing MySQL using cluster rpm

Install MySQL database a) Download the MySQL sour...

How to solve the problem of case insensitivity in MySQL queries

question Recently, when I was completing a practi...

How to use union all in MySQL to get the union sort

Sometimes in a project, due to some irreversible ...

mysql 5.7.18 winx64 password change

After MySQL 5.7.18 is successfully installed, sin...

MySQL exposes Riddle vulnerability that can cause username and password leakage

The Riddle vulnerability targeting MySQL versions...

Linux Jenkins configuration salve node implementation process diagram

Preface: Jenkins' Master-Slave distributed ar...

Detailed tutorial on building Gitlab server on CentOS8.1

There is no need to say much about the difference...

Docker and portainer configuration methods under Linux

1. Install and use Docer CE This article takes Ce...

MySQL Workbench download and use tutorial detailed explanation

1. Download MySQL Workbench Workbench is a graphi...

MySQL replication mechanism principle explanation

Background Replication is a complete copy of data...

A brief analysis of the matching priority of Nginx configuration location

Preface The location in the server block in the N...

Detailed steps for installing JDK and Tomcat on Linux cloud server (recommended)

Download and install JDK Step 1: First download t...

Question about custom attributes of html tags

In previous development, we used the default attr...