当前位置:网站首页>Inheritance of ES6 class
Inheritance of ES6 class
2022-07-03 17:33:00 【Xiaozhuang classmate】
Hello everyone , I am Xiaozhuang .
Let's sort it out today ES6 Inheritance in .
Incidentally, record the knowledge points that are easy to forget .
1、extends keyword
actually , The key to inheritance is extends:
class myClass{
}
class children extends myClass{
}
analysis : Through the top extends Inherited myClass All properties and methods of .
2、super keyword
super Keywords have two completely different forms in classes :
1、 When representing functions, use
ES6 requirement , The constructor for the subclass must be executed once super function . Represents the constructor of the parent class . As a function ,super() It can only be used in the constructor of a subclass , Use it elsewhere and you'll get an error .
class A {}
class B extends A {
constructor() {
super();
}
}
Above super Although it means A Constructor for , However, it returns subclasses B Example . namely super Inside this refer to B Example .
The above jargon is explained by code :
A.prototype.constructor.call(this).
2、 Use when representing objects
super As an object , In the ordinary way , Points to the prototype object of the parent class ; In a static method , Point to the parent class .
Although I personally think this design will undoubtedly increase programmers' understanding of super The difficulty of understanding , But familiarity is good . To distinguish what is the prototype object and the object itself .
class A {
constructor() {
this.a = 2;
}
p() {
return 2;
}
}
class B extends A {
constructor() {
super();
console.log(super.p()); // 2
}
get m() {
return super.a; // undefined
}
}
let b = new B();
b.m;
super.p() It is obviously used as an object , Here, it refers to the prototype object of the parent class , and p The method is defined in A On the prototype of , So the return value is 2. Naturally call b.m You can't get the value .
This is also illustrated from the side :constructor() Generally speaking, the method is only A In itself , The general methods in a class are defined on the prototype object of the class .
Let's take another example :
class A {
constructor() {
this.x = 1;
}
print() {
console.log(this.x);
}
}
class B extends A {
constructor() {
super();
this.x = 2;
}
m() {
super.print();
}
}
let b = new B();
b.m()
Guess what will be output in the end ,1 perhaps 2?
From some of the above , call print Method , and print The method is defined in A Class , Should the printed value be 1 Well ?
The answer is 2. This JS The execution scope of the function is related .
How to understand ?
When the function is executed, a scope will be generated , Run to the b.m() when , Will create a file that belongs to m A context of ,m Inside this Point to himself ,print When called , The engine will be there first print Look inside this.x, If you don't find it, go to the upper level of the operation to find , I found it m,m If you don't have one, go m Define the upper level to find , If you haven't found it yet, look up level by level , Find out constructor There's a variable in x, Stop and continue searching .
If you change the above slightly B Code for :
class B extends A {
constructor() {
super();
}
m() {
super.print();
}
}
let b = new B();
b.m()
here , The answer is 1.
because B Inherited A,B The archetype of this is pointing to A Of , stay B If you can't find it, you'll go A In looking for , So the answer is 1.
To strengthen memory, let's take another example :
class A {
constructor() {
this.x = 1;
}
}
class B extends A {
constructor() {
super();
this.x = 2;
super.x = 3;
console.log(super.x); // undefined
console.log(this.x); // 3
}
}
let b = new B();
What is a print value ?
Some students said confidently that it was not 1 Well .
The answer is wrong .
When in subclass B Call in super(); Remember what it stands for ?
A.prototype.constructor.call(this).
Yes ,super.x = 3; Actually, it refers to subclasses B in x Assignment , amount to this.x=3.
And in the output super.x when , Execution is A.prototype.x. and A There is no x So it will output undefined.
Although it seems a little windy , But it still makes sense . Obviously, the value of the second output is 3.
Add code that helps understand :
class A {
constructor() {
this.x = 1;
}
test() {
console.log(' Here is the test ');
}
y = 2
}
class B extends A {
constructor() {
super();
this.x = 2;
// super.x = 3, Actually, it refers to subclasses B in x Assignment , amount to this.x=3
super.x = 3;
// super.test = function testFun() {}, amount to this.test = function testFun(){}
super.test = function testFun() {
console.log(' Performed the test here ');
}
// super.testB = function() {}, amount to this.testB = function(){}
super.testB = function() {
console.log(' Here is the modified testB function ');
}
console.log(super.test());// ' Here is the test '
console.log(super.y);// undefined
console.log(super.x); // undefined
console.log(this.x); // 3
}
testB() {
console.log(' Here is testB function ');
}
}
let b = new B();
b.test(); // ' Performed the test here '
b.testB(); // ' Here is the modified testB function '
3、 Class prototype Properties and __proto__ attribute
It's a detour again , Just be familiar with that sentence . Although I think this design is really not so reasonable .
Class as constructor , So have prototype Attributes are also taken for granted . that __proto__ Where do attributes come from ?
JS Everything is object , Although not accurate, classes are indeed a kind of objects , therefore __proto__ came , Someone put __proto__ It's called implicit prototype , Actually, it's not right .proto__ As JS The bridge of prototype chain , It's just that this attribute is exposed to different degrees in different browsers ,Google You can access the... Of the object __proto. The question about the prototype chain is left for separate explanation later , Back to class , Classes also have prototype Properties and __proto__ attribute , So the prototype chain of the class is like this :
class A {
}
class B extends A {
}
B.__proto__ === A // true
B.prototype.__proto__ === A.prototype // true
You'll probably see from it prototype and __proto__ The difference between .
These two inheritance chains , It can be understood in this way : As an object , Subclass (B) The prototype of the (__proto__ attribute ) Parent class (A); As a constructor , Subclass (B) Prototype object (prototype attribute ) Is the prototype object of the parent class (prototype attribute ) Example .
From this we can see that :
Prototypes of subclasses __proto__ Parent class , Then the prototype of the subclass is the prototype of the parent .
4、 Add
Official account :【 Deep drift programmer Xiaozhuang 】, It contains rich learning resources and interview experience ( Not limited to the front end 、java、 Algorithm ), There are also learning exchange groups to add , In addition, there are leaders of major factories who can exchange and learn together , Progress together ~ Add Xiaozhuang wechat , reply 【 Add group 】, You can join the Internet technology exchange group .
边栏推荐
- POM in idea XML graying solution
- Golang unit test, mock test and benchmark test
- PR second time
- Dagong 21 autumn "power plant electrical part" online operation 1 [standard answer] power plant electrical part
- UE4 official charging resources, with a total price of several thousand
- Leetcode540: a single element in an ordered array
- 【JokerのZYNQ7020】DDS_ Compiler。
- 1164 Good in C
- QT adjust win screen brightness and sound size
- Kubernetes resource object introduction and common commands (V) - (NFS & PV & PVC)
猜你喜欢

【RT-Thread】nxp rt10xx 设备驱动框架之--Audio搭建和使用

Test your trained model

Cloud primordial weekly | CNCF released the 2021 cloud primordial development status report, which was released on istio 1.13

STM32实现74HC595控制
![[error reporting] omp: error 15: initializing libiomp5md dll, but found libiomp5md. dll already initialized.](/img/a0/4fc0e0741aad2885873e60f2af3387.jpg)
[error reporting] omp: error 15: initializing libiomp5md dll, but found libiomp5md. dll already initialized.

SWM32系列教程4-端口映射及串口应用

One brush 149 force deduction hot question-10 regular expression matching (H)

Applet setting multi account debugging

Leetcode Valentine's Day Special - looking for a single dog

Wechat applet for the first time
随机推荐
How to train mask r-cnn model with your own data
鸿蒙第四次培训
Internet hospital his management platform source code, online consultation, appointment registration smart hospital applet source code
Detailed explanation of common network attacks
PHP processing - watermark images (text, etc.)
vs code 插件 koroFileHeader
Javescript variable declaration -- VaR, let, const
【RT-Thread】nxp rt10xx 设备驱动框架之--hwtimer搭建和使用
Financial management (Higher Vocational College) financial management online Assignment 1 in autumn 20
绝对定位时元素水平垂直居中
远程办公工具分享|社区征文
RDS数据库的监测页面在哪看?
Unity notes unityxr simple to use
Vs code plug-in korofileheader
Where is the monitoring page of RDS database?
How do large consumer enterprises make digital transformation?
PHP returns 500 errors but no error log - PHP return 500 error but no error log
[combinatorics] recursive equation (general solution structure of recursive equation with multiple roots | linear independent solution | general solution with multiple roots | solution example of recu
PUT vs. POST for Uploading Files - RESTful API to be Built Using Zend Framework
2021 ICPC regional competition (Shanghai) g.edge groups (tree DP)