This article describes the inheritance method of JavaScript class. Share it for your reference, as follows:
In JavaScript, the inherited functions are called supertypes (parent class, base class, and other languages are also called), and the inherited functions are called subtypes (subclass, derived class). Inheritance also has previous problems, such as literal rewriting prototypes will break the relationship, use the prototype of the reference type, and the subtype cannot pass parameters to the supertype.
In order to solve the problem of reference sharing and supertypes that cannot be passed through parameters, we use a technology called borrowing constructors, or a technology that becomes an object impersonation (forgetting objects, classic inheritance) to solve these two problems.
function aObj(){ = ['Little Red','Xiaoqiang']; } } = ()=>{ alert() } function bObj(){ (this); //Inheritance only for the constructor itself, the prototype needs to be inherited.}
Although borrowing the constructor solves the inheritance of the function itself, it does not inherit the prototype chain. Therefore, we need a pattern of prototype chain + borrow constructor, which is called combinatorial inheritance.
Method 1:
= ;
shortcoming:Reference type, when operating the object prototype, directly change the object in the heap memory method
Method 2:
= new aObj();
This kind of inheritance uses the help of a prototype and creates new objects based on existing objects, and does not have to create a custom type because of this, but the constructor inherits twice, which is not very good.
Method 3:
= (); = bObj
Use the a prototype object and its properties to create a new object and point the constructor of this object to the B function itself. There is no problem of repeated inheritance.
Method 4:
for (var i in ) { [i] = [i]; }
Iterate the prototype chain of a to object b to realize the deep copy of the prototype, and both parties will not affect each other.
For more information about JavaScript, readers who are interested in reading this site's special topic:JavaScript object-oriented tutorial》、《Summary of JavaScript Errors and Debugging Skills》、《Summary of JavaScript data structure and algorithm techniques》、《JavaScript traversal algorithm and skills summary"and"Summary of JavaScript mathematical operations usage》
I hope this article will be helpful to everyone's JavaScript programming.