当前位置:网站首页>JS inheritance
JS inheritance
2022-06-30 04:09:00 【Runqing】
ES6 Inheritance
class Parent0 {
constructor (name = 'parents0') {
this.name = name
}
}
class Child0 extends Parent0 {
constructor (type = 'child0') {
super()
// When there is no need to define additional attributes beyond the parent class ,constructor and super All can be omitted , Constructors implicitly execute .
this.type = type
}
}
let s0 = new Child0();
console.log(s0) // {name: "parents6", type: "child6"}
ES5 Several inheritance methods and their advantages and disadvantages :
( Supplementary knowledge ) Prototype chain
- Constructor's prototype Where does the attribute point to , Of the object it instantiates __proto__ The attribute points to where .
- An object instance constructor Where does the attribute point to , Not by which constructor it is constructed new Coming out , But look at its __proto__ In the prototype of the object pointed to constructor Who is it . That is, the of the instance object constructor Attributes are also from __proto__ Inherited from the prototype object .( for instance , Under normal circumstances , Constructors prototype To which object prototype , Which object prototype points to it . If it is an artificial constructor A Of prototype Point to something constructed by other constructors B Instance object of C when , Then the instance object will not be changed C The original constructor by B, And that leads to A Constructors new Out object D Of constructor It's also B.)
- Through the... In the constructor new The object instance , Constructor has properties , Every new Each object has its own attribute . Properties and methods on prototype objects , Is common to all instance objects .
1. Inheritance with the help of constructor : Execute the constructor of the parent class in the constructor body of the child class .

// Parent class
function Parent1 () {
this.name = 'parent1';
}
Parent1.prototype.say = function () {
};
// Subclass
function Child1 () {
// a key : The principle is embodied in this sentence
Parent1.call(this);
// Subclass's own properties
this.type = 'child1';
}
// Object instances do not inherit properties and methods from parent class stereotype , There will be an error when calling
console.log(new Child1(), new Child1().say());// Report errors :say is not a function
principle : Execute the constructor of the parent in the function body of the subclass , At the same time, change the context of function operation ( That is to say this The direction of ), send this Point to Child1 This class , As a result, the properties of the parent class will be attached to the child class , In this way, inheritance is realized .
shortcoming : Only partial inheritance is implemented . Just inherit the attributes in the parent class , But the properties in the prototype of the parent class cannot inherit . because say Is added to the prototype of the parent class , This inheritance method only changes the direction of the parent constructor in the body of the subclass function , Can not inherit the properties of the prototype .
2. Inheritance with the help of prototype chain ( Let subclass constructor prototype Point to the instance of the parent class , So as to inherit the properties of the parent class and the properties on the prototype object of the parent class )

function Parent2 () {
this.name = 'parent2';
this.play = [1, 2, 3];
}
function Child2 () {
this.type = 'child2';
}
// a key : Through the Child2 The prototype of points to Parent2 To implement inheritance
Child2.prototype = new Parent2();
// This makes Child2() Object __proto__ Property becomes a parent class Parent2 Instance object of .
var s1 = new Child2();
var s2 = new Child2();
console.log(s1.play, s2.play);
// Don't add 4, Print the results :[1,2,3],[1,2,3].
// increase 4 after
s1.play.push(4);
// Print the results :[1,2,3,4],[1,2,3,4]
shortcoming : We only changed s1 The properties of this instance , But found Child2 The properties of the other instances of are changed together .
reason :s1,s2 Share the same prototype object . namely s1.proto === s2.proto. And the play The array is on that instance object .s1 What is modified is the properties of its prototype , Property modification of prototype , The properties of all classes that inherit from the stereotype change together , therefore Child2 There is no isolation between instances of , That's clearly not what we want .
3. combination
The combination method is the combination of the constructor of the first two methods and the prototype chain , This method solves the shortcomings of the above two methods .
function Parent3 () {
this.name = 'parent3';
this.play = [1, 2, 3];
}
function Child3 () {
// The superclass constructor is executed in the subclass
Parent3.call(this);
this.type = 'child3';
}
// The prototype of the subclass points to the parent class
Child3.prototype = new Parent3();
var s3 = new Child3();
var s4 = new Child3();
s3.play.push(4);
console.log(s3.play, s4.play);
// Print the results :[1,2,3,4] , [1,2,3]
It can be seen that , Modify the properties of an instance , It does not change the properties of the parent class . This way of inheritance combines the advantages of constructor and prototype chain inheritance , And make up for their shortcomings , There are no shortcomings in the function .
But every time you create an instance , Constructor will be executed twice, which is unnecessary , Because when you inherit the constructor , That is to say Parent3.call(this) When ,parnet The attribute of is already in child It's running , When the external prototype chain inherits, there is no need to execute it again .
shortcoming :
1) Because when creating an instance of a subclass , The constructor of the parent class is executed twice .
2) You can see s3 yes new Child3() Coming out , But his constructor nevertheless Parent3.
4. Optimization of combination mode ( Solve the inheritance method 3 The first disadvantage of )

The problem with the above inheritance method is that the constructor of the parent class is executed again when inheriting the prototype , The constructor of the parent class is executed twice . So optimization starts from this point .
In the combination mode, in order to solve the problem of inheritance by constructor ( That is, the first one in this article ) The shortcomings of , Properties in the prototype of the parent class cannot inherit , That's why the prototype of the child class points to the instance of the parent class .
But the properties of the parent class , It already exists in the subclass , Subclasses simply lack attributes in the prototype of the parent class , therefore , According to this , We optimize .
function Parent4 () {
this.name = 'parent4';
this.play = [1, 2, 3];
}
function Child4 () {
Parent4.call(this);
this.type = 'child4';
}
// The child object prototype refers to the parent object prototype
Child4.prototype = Parent4.prototype;
var s5 = new Child4();
var s6 = new Child4();
console.log(s5, s6);
console.log(s5 instanceof Child4, s5 instanceof Parent4);// true true
console.log(s5.constructor);// f Parent4(){this.name = 'parent4';this.play = [1,2,3];}
In this way of inheritance , It doesn't directly point the prototype of the child class to the parent class , Instead, it points to the prototype of the parent class . This avoids the second execution of the parent constructor , Thus, the optimization of the combination mode is completed . But there is still a small problem , Output results , You can see s5 yes new Child4() Coming out , But his constructor nevertheless Parent4.
shortcoming : That is, the instance object of the subclass created by this method cannot distinguish whether it is instantiated by the subclass or the parent class .
reason : This is because Child4 There is no constructor property in this class , Its constructor is taken from the upper level of the prototype chain , That is to say Parent4.
5. Perfect optimization of the combination ( common 3 Step )( Solve the inheritance method 3 Two disadvantages )

function Parent5 () {
this.name = 'parent5';
this.play = [1, 2, 3];
}
function Child5 () {
//1. Call the constructor of the parent class from the constructor of the child class
Parent5.call(this);
this.type = 'child5';
}
//2. Point the prototype of the subclass to pass Object.create Intermediate objects created
Child5.prototype = Object.create(Parent5.prototype);
//3. hold Child5 The constructor of the prototype points to itself
Child5.prototype.constructor = Child5;
// test
var s7= new Child5();
console.log(s7 instanceof Child5, s7 instanceof Parent5)// true true
console.log(s7.constructor);// f Child5(){}
By pointing the prototype of the subclass to Object.create(Parent5.prototype), It realizes the separation of the constructor of the subclass and the constructor of the parent class , But there is still no constructor in the subclass , So the constructor of the subclass is set immediately , Thus, the perfect combination inheritance is realized .
边栏推荐
- NER中BiLSTM-CRF解读score_sentence
- base64.c
- Quick sort & merge sort
- Ananagrams(UVA156)
- Interface testing -- how to analyze an interface?
- 基于海康EhomeDemo工具排查公网部署出现的视频播放异常问题
- UML diagrams and list collections
- Troubleshoot abnormal video playback problems in public network deployment based on Haikang ehomedemo tool
- Analysis of similarities and differences of various merged features (Union, merge, append, resolve) in ArcGIS
- DRF -- nested serializer (multi table joint query)
猜你喜欢

You know AI, database and computer system

dotnet-exec 0.5.0 released

Share an example of a simple MapReduce method using a virtual machine

EasyCVR部署服务器集群时,出现一台在线一台不在线是什么原因?

Analysis of similarities and differences of various merged features (Union, merge, append, resolve) in ArcGIS

华为云原生——数据开发与DataFactory

Node red series (28): communication with Siemens PLC based on OPC UA node

lego_ Reading and summary of loam code

Troubleshoot abnormal video playback problems in public network deployment based on Haikang ehomedemo tool

How to analyze and solve the problem of easycvr kernel port error through process startup?
随机推荐
[operation] MySQL query on May 24, 2022
Robot slam navigation core technology and practice Season 1: Chapter 0_ Slam development overview
[operation] write CSV to database on May 28, 2022
The same node code will cause duplicate data
DRF -- nested serializer (multi table joint query)
Troubleshoot abnormal video playback problems in public network deployment based on Haikang ehomedemo tool
第九天 脚本與資源管理
(03).NET MAUI实战 基础控件
接口测试--如何分析一个接口?
Unity 在编辑器中输入字符串时,转义字符的输入
Selenium environment installation, 8 elements positioning --01
lego_loam 代码阅读与总结
AI落地的新范式,就“藏”在下一场软件基础设施的重大升级里
Blue Bridge Cup: magic cube rotation [Vocational group]
Interface test tool postman
After the win10 system uses the browser to download, the content is moved or deleted without reason
An error occurs when sqlyog imports the database. Please help solve it!
【图像融合】基于交叉双边滤波器和加权平均实现多焦点和多光谱图像融合附matlab代码
Idea grey screen problem
The school training needs to make a registration page. It needs to open the database and save the contents entered on the registration page into the database