当前位置:网站首页>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 .
边栏推荐
- Unity 在編輯器中輸入字符串時,轉義字符的輸入
- Unity 在编辑器中输入字符串时,转义字符的输入
- 【论文阅读|深读】Role2Vec:Role-Based Graph Embeddings
- How to use FME to create your own functional software
- 基于海康EhomeDemo工具排查公网部署出现的视频播放异常问题
- el-upload上传文件(手动上传,自动上传,上传进度)
- Node red series (28): communication with Siemens PLC based on OPC UA node
- SQLyog导入数据库时报错,求帮解决!
- errno和perror
- Solutions for project paths
猜你喜欢

Interpretation score of bilstm-crf in NER_ sentence

巧用 Bitmap 实现亿级海量数据统计

DBT product initial experience

第十天 数据的保存与加载

如何通过进程启动来分析和解决EasyCVR内核端口报错问题?
![[note] on May 27, 2022, MySQL is operated through pychart](/img/34/36a3765683b2af485ca7c3e366da59.png)
[note] on May 27, 2022, MySQL is operated through pychart

你清楚AI、数据库与计算机体系

RPC correction

【云原生】AI云开发平台——AI Model Foundry介绍(开发者可免费体验AI训练模型)
![Blue Bridge Cup: magic cube rotation [Vocational group]](/img/ba/aeae2744f3aaa1052b5af452f990e2.jpg)
Blue Bridge Cup: magic cube rotation [Vocational group]
随机推荐
How to solve the problem of link hyperlinks when trying to link the database?
mysql更新数组形式的json串
An error occurs when sqlyog imports the database. Please help solve it!
Pig-Latin (UVA492)
尝试链接数据库时出现链接超时报错,如何解决?
The same node code will cause duplicate data
[punch in - Blue Bridge Cup] day 3 --- slice in reverse order list[: -1]
如何利用FME 创建自己的功能软件
You know AI, database and computer system
lego_loam 代码阅读与总结
(04). Net Maui actual MVVM
Implementation of aut, a self-developed transport layer protocol for sound network -- dev for dev column
第十一天 脚本与游戏AI
Jour 9 Gestion des scripts et des ressources
Unity 在編輯器中輸入字符串時,轉義字符的輸入
(03).NET MAUI实战 基础控件
Selenium environment installation, 8 elements positioning --01
A minimalist way to integrate databinding into activity/fragment
第九天 脚本与资源管理
oslo_ config. cfg. ConfigFileParseError: Failed to parse /etc/glance/glance-api. Conf: a solution to errors