当前位置:网站首页>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 .
边栏推荐
- [punch in - Blue Bridge Cup] day 3 --- slice in reverse order list[: -1]
- (03).NET MAUI实战 基础控件
- [fuzzy neural network prediction] water quality prediction based on fuzzy neural network, including Matlab source code
- 两个月拿到N个offer,什么难搞的面试官在我这里都不算事
- 绿色新动力,算力“零”负担——JASMINER X4系列火爆热销中
- DRF -- nested serializer (multi table joint query)
- El upload Upload file (Manual upload, Automatic upload, upload progress)
- Node-RED系列(二八):基于OPC UA节点与西门子PLC进行通讯
- Everyone, Flink 1.13.6, mysql-cdc2.2.0, the datetime (6) class extracted
- [punch in - Blue Bridge Cup] day 2 --- format output format, ASCII
猜你喜欢

两个月拿到N个offer,什么难搞的面试官在我这里都不算事

【模糊神经网络预测】基于模糊神经网络实现水质预测含Matlab源码

DBT product initial experience

Linear interpolation of spectral response function

Do280 private warehouse persistent storage and chapter experiment

毕业设计EMS办公管理系统(B/S结构)+J2EE+SQLserver8.0

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

第九天 脚本与资源管理

I spent three years in a big factory outsourcing, which subverted my understanding!

DO280私有仓库持久存储与章节实验
随机推荐
Day 9 script and resource management
Thinkphp5 implements import function
RPC correction
[operation] MySQL query operation 2 on May 25, 2022
Technology sharing | broadcast function design in integrated dispatching
The jupyter notebook kernel hangs up frequently and needs to be restarted
(03). Net Maui actual combat basic control
Sql语句遇到的错误,求解
华为云原生——数据开发与DataFactory
接口测试--如何分析一个接口?
云原生入门+容器概念介绍
关于智能视觉组上的机械臂
If you encounter problems when using spark for the first time, please ask for help
Green new power and "zero" burden of computing power -- JASMINER X4 series is popular
01 backpack, dynamic planning
云原生——Web实时通信技术之Websocket
(04). Net Maui actual MVVM
ReSharper 7. Can X be used with vs2013 preview? [off] - can resharper 7 x be used with VS2013 preview? [closed]
thinkphp5实现导入功能
SQLyog导入数据库时报错,求帮解决!