当前位置:网站首页>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 .
边栏推荐
- Great changes! National housing prices fell below the 10000 yuan mark
- [combinatorics] recursive equation (special solution example 1 Hannover tower complete solution process | special solution example 2 special solution processing when the characteristic root is 1)
- Wechat applet for the first time
- 2021 ICPC regional competition (Shanghai) g.edge groups (tree DP)
- 鸿蒙第四次培训
- Collection of the most beautiful graduation photos in the graduation season, collection of excellent graduation photos
- 绝对定位时元素水平垂直居中
- Internet Hospital his Management Platform source, online Inquiry, appointment Registration Smart Hospital Small program source
- New library online | cnopendata complete data of Chinese insurance institution outlets
- Redis: operation commands for list type data
猜你喜欢
Golang unit test, mock test and benchmark test
问题随记 —— 在 edge 上看视频会绿屏
Type conversion, variable
【RT-Thread】nxp rt10xx 设备驱动框架之--Audio搭建和使用
Free data | new library online | cnopendata complete data of China's insurance intermediary outlets
Luogu: p2685 [tjoi2012] Bridge
One brush 147-force deduction hot question-4 find the median of two positive arrays (H)
互聯網醫院HIS管理平臺源碼,在線問診,預約掛號 智慧醫院小程序源碼
[combinatorics] recursive equation (summary of the solution process of recursive equation | homogeneous | double root | non-homogeneous | characteristic root is 1 | exponential form | the bottom is th
QT adjust win screen brightness and sound size
随机推荐
Kubernetes resource object introduction and common commands (III)
Leetcode540: a single element in an ordered array
September, 19, "cam principle and application" online assignment [Full Score answer]
Assignment examination questions of advanced English (III) for the course examination of Fujian Normal University in February 2022
LeetCode13.罗马数字转整数(三种解法)
Dagong 21 autumn "power plant electrical part" online operation 1 [standard answer] power plant electrical part
Hongmeng third training
Financial management (Higher Vocational College) financial management online Assignment 1 in autumn 20
Answer to the homework assessment of advanced English reading (II) of the course examination of Fuzhou Normal University in February 2022
Brief introduction to the core functions of automatic penetration testing tool
设计电商秒杀
link preload prefetch
Applet setting multi account debugging
Free data | new library online | cnopendata complete data of China's insurance intermediary outlets
Apache服务挂起Asynchronous AcceptEx failed.
Leetcode13. Roman numeral to integer (three solutions)
Wechat applet for the first time
Kotlin学习快速入门(7)——扩展的妙用
The difference between i++ and ++i: tell their differences easily
Stm32h7 Hal library SPI DMA transmission has been in busy solution