当前位置:网站首页>ES6 deep - ES6 class class
ES6 deep - ES6 class class
2022-07-05 16:04:00 【Braised snapper with orange cat】
List of articles
Preface
This article will briefly introduce ES6 Class Class knowledge , How to define how to use , Through this experiment , Need to master ES6 Definition and use of middle classes .
One 、 Basic usage
Class definition
Class expressions can be anonymous or named .
// An anonymous class
let ExampleA = class {
constructor(count) {
this.count = count;
}
};
// Name the class
let ExampleB = class ExampleB {
constructor(a) {
this.a = a;
}
};
Class declaration
class ExampleC {
constructor(a) {
this.a = a;
}
}
- Pay attention to the point : Cannot repeat declaration , Otherwise an error .
class ExampleA {
}
class ExampleA {
}
// Uncaught SyntaxError: Identifier 'ExampleA' has already been
// declared
let Example1 = class {
};
class ExampleA {
}
// Uncaught SyntaxError: Identifier 'Example' has already been
// declared
- Be careful : The class must be defined before accessing , Otherwise you will report an error . Methods in a class do not require function keyword . Semicolons cannot be added between methods .
new Example();
class Example {}
Steps are as follows :
- Create name as test1.js The file of , And enter the following code .
// An anonymous class
let ExampleA = class {
constructor(count) {
this.count = count;
}
};
// Name the class
let ExampleB = class ExampleB {
constructor(a) {
this.a = a;
}
};
console.log(ExampleA);
console.log(ExampleB);
- Run at terminal , The results are shown below :
Two 、 Class
attribute prototype
ES6 in ,prototype It still exists , Although methods can be defined directly in classes , But in fact, the method is still defined in prototype Upper . Override method / The adding method during initialization is as follows :
ExampleA.prototype = {
// methods
};
Add method :
Object.assign(ExampleA.prototype, {
// methods
});
Static attribute
Static attribute :class Its own attributes , That is, attributes defined directly inside the class ( Class.propname ), There is no need to instantiate .ES6 Specified in the ,Class There are only static methods inside , No static properties .
class ExampleD {
a = 2;
constructor() {
console.log(this.a);
}
}
name attribute
Return to follow class Class name after ( In existence ).
let ExampleE = class Exam {
constructor(a) {
this.a = a;
}
};
console.log(ExampleE.name); // Exam
let ExampleF = class {
constructor(a) {
this.a = a;
}
};
console.log(ExampleF.name); // ExampleF
example :
Create name as test2.js The file of , And enter the following code .
// Static attribute
class ExampleA {
// New proposal
static a = 3;
}
// At present, it is feasible to write
ExampleA.b = 3;
// Public attribute
class ExampleB {
}
ExampleB.prototype.a = 2;
// Instance attributes
class ExampleC {
a = 2;
constructor() {
console.log(this.a);
}
}
// name attribute
let ExampleD = class ExamD {
constructor(a) {
this.a = a;
}
};
console.log(ExampleD.name); // Exam
let ExampleE = class {
constructor(a) {
this.a = a;
}
};
console.log(ExampleE.name); // Example
Run at terminal , The results are shown below :
3、 ... and 、 Method
constructor Method
constructor Method is the default method of a class , Called when creating an instantiated object of a class .
class Example {
constructor() {
console.log(" I am a constructor");
}
}
new Example(); // I am a constructor
Returns the object
class Test {
constructor() {
// Returns the instance object by default this
}
}
console.log(new Test() instanceof Test); // true
class Example {
constructor() {
// Specifies the return object
return new Test();
}
}
console.log(new Example() instanceof Example); // false
Static methods
class Example {
static sum(a, b) {
console.log(a + b);
}
}
Example.sum(1, 2); // 3
Prototype method
class Example {
constructor() {
this.sum = (a, b) => {
console.log(a + b);
};
}
}
Example method
class Example {
constructor() {
this.sum = (a, b) => {
console.log(a + b);
};
}
}
example :
Create name as test3.js The file of , And enter the following code .
// constructor Method
class Example {
constructor() {
console.log(" I am a constructor");
}
}
new Example(); // I am a constructor
// Returns the object
class Test {
constructor() {
// Returns the instance object by default this
}
}
console.log(new Test() instanceof Test); // true
class ExampleB {
constructor() {
// Specifies the return object
return new Test();
}
}
console.log(new Example() instanceof ExampleB); // false
// Static methods
class ExampleD {
static sum(a, b) {
console.log(a + b);
}
}
ExampleD.sum(1, 2); // 3
// Prototype method
class ExampleE {
constructor() {
this.sum = (a, b) => {
console.log(a + b);
};
}
}
// Example method
class ExampleF {
constructor() {
this.sum = (a, b) => {
console.log(a + b);
};
}
}
Run at terminal , The results are shown below :
Four 、 Class instantiation
new
Class instantiation , Must pass new keyword .
class ExampleG {
}
let exam1 = ExampleG();
// Class constructor Example cannot be invoked without 'new'
Instantiate objects
Share prototype objects .
class ExampleH {
constructor(m, n) {
this.m = m;
this.n = n;
console.log("ExampleH");
}
sum() {
return this.m + this.n;
}
}
let exam1 = new ExampleH(5, 3);
let exam2 = new ExampleH(2, 7);
console.log(exam1._proto_ == exam2._proto_); // true
exam1.__proto__.sub = function () {
return this.a - this.b;
};
console.log(exam1.sum()); // 8
console.log(exam2.sum()); // 9
example :
Create name as test4.js The file of , And enter the following code .
class ExampleH {
constructor(m, n) {
this.m = m;
this.n = n;
console.log("ExampleH");
}
sum() {
return this.m + this.n;
}
}
let exam1 = new ExampleH(5, 3);
let exam2 = new ExampleH(2, 7);
console.log(exam1._proto_ == exam2._proto_); // true
exam1.__proto__.sub = function () {
return this.a - this.b;
};
console.log(exam1.sum()); // 8
console.log(exam2.sum()); // 9
Run at terminal , The results are shown below :
5、 ... and 、decorator
decorator It's a function , Used to modify the behavior of a class , It works when the code is compiled .
Class decoration
One parameter .
The first parameter target, Point to the class itself .
function testable(target) {
target.isTestable = true;
}
@testable
class Example {
}
Example.isTestable; // true
Multiple parameters —— Nested implementation .
function testable(isTestable) {
return function (target) {
target.isTestable = isTestable;
};
}
@testable(true)
class Example {
}
Example.isTestable; // true
Instance attributes , The above two examples add static attributes , To add instance properties , In class prototype Just operate it .
Method modification
3 Parameters :target( Class )、name( Modified property name )、descriptor( The description object of this attribute ).
class Example {
@writable
sum(a, b) {
return a + b;
}
}
function writable(target, name, descriptor) {
descriptor.writable = false;
return descriptor; // Must return
}
Decorator execution sequence
Enter from outside to inside , From inside to outside .
class Example {
@logMethod(1)
@logMthod(2)
sum(a, b) {
return a + b;
}
}
function logMethod(id) {
console.log("evaluated logMethod" + id);
return (target, name, desctiptor) =>
console.log("excuted logMethod " + id);
}
// evaluated logMethod 1
// evaluated logMethod 2
// excuted logMethod 2
// excuted logMethod 1
6、 ... and 、 Encapsulation and inheritance
getter / setter
The definitions are as follows :
class Example {
constructor(a, b) {
this.a = a; // Call... When instantiating set Method
this.b = b;
}
get a() {
console.log("getter");
return this.a;
}
set a(a) {
console.log("setter");
this.a = a; // Call itself recursively
}
}
let exam = new Example(1, 2); // Keep outputting setter, Eventually lead to RangeError
class Example1 {
constructor(a, b) {
this.a = a;
this.b = b;
}
get a() {
console.log("getter");
return this._a;
}
set a(a) {
console.log("setter");
this._a = a;
}
}
let exam1 = new Example1(1, 2); // Only the output setter, Not invoke getter Method
console.log(exam._a); // 1, You can directly access
establish The name is test5.js The file of , And enter the following code .
class Example {
constructor(a, b) {
this.a = a; // Call... When instantiating set Method
this.b = b;
}
get a() {
console.log("getter");
return this.a;
}
set a(a) {
console.log("setter");
this.a = a; // Call itself recursively
}
}
let exam = new Example(1, 2); // Keep outputting setter, Eventually lead to RangeError
class Example1 {
constructor(a, b) {
this.a = a;
this.b = b;
}
get a() {
console.log("getter");
return this._a;
}
set a(a) {
console.log("setter");
this._a = a;
}
}
let exam1 = new Example1(1, 2); // Only the output setter, Not invoke getter Method
console.log(exam._a); // 1, You can directly access
Input... At the terminal node test5.js function , The results are shown below :
- A special case :getter Do not appear alone .
class Example {
constructor(a) {
this.a = a;
}
get a() {
return this.a;
}
}
let exam = new Example(1); // Uncaught TypeError: Cannot set property // a of #<Example> which has only a getter
- The main points of :getter And setter Must appear at the same level .
class Father {
constructor() {
}
get a() {
return this._a;
}
}
class Child extends Father {
constructor() {
super();
}
set a(a) {
this._a = a;
}
}
let test = new Child();
test.a = 2;
console.log(test.a); // undefined
class Father1 {
constructor() {
}
// Or put them all in subclasses
get a() {
return this._a;
}
set a(a) {
this._a = a;
}
}
class Child1 extends Father1 {
constructor() {
super();
}
}
let test1 = new Child1();
test1.a = 2;
console.log(test1.a); // 2
Create name as test6.js The file of , And enter the code above .
Input... At the terminal node test6.js Post run , The results are shown below :
extends
adopt extends Implementation class inheritance .
class Child extends Father {
... }
7、 ... and 、super
Subclass constructor There must be... In the method super, And must appear in this Before , The following code is not super Function causes an error .
class Father {
constructor() {}
}
class Child extends Father {
constructor() {}
// or
// constructor(a) {
// this.a = a;
// super(); // There must be , without super() Will report a mistake
// }
}
let test = new Child(); // Uncaught ReferenceError: Must call super
// constructor in derived class before accessing 'this' or returning
// from derived constructor
Pay attention to the point
Regular objects cannot be inherited .
var Father = {
// ...
};
class Child extends Father {
// ...
}
// Uncaught TypeError: Class extends value #<Object> is not a constructor or null
// Solution
Object.setPrototypeOf(Child.prototype, Father);
Create name as test7.js The file of , And enter the following code .
class Father {
constructor() {
}
}
class Child extends Father {
constructor(a) {
super();
this.a = a;
console.log(a); // print 12
}
}
let test = new Child(12);
test;
Input... At the terminal node test7.js function , The results are shown below :
![ Please add a picture description ](https://img-blog.csdnimg.cn/4509b3f5e73e4cf197c4235c9d0a5406.png)
# summary
This paper introduces ES6 Class Of ES6 Class definition and usage constructor() Method 、Class Expression and super keyword .
The following explains ES6 Generator function .
边栏推荐
- RepLKNet:不是大卷积不好,而是卷积不够大,31x31卷积了解一下 | CVPR 2022
- Lesson 4 knowledge summary
- 16. [stm32] starting from the principle, I will show you the DS18B20 temperature sensor - four digit digital tube displays the temperature
- How difficult is it to pass the certification of Intel Evo 3.0? Yilian technology tells you
- RLock锁的使用
- 效果编辑器新版上线!3D渲染、加标注、设置动画,这次一个编辑器就够了
- 17. [stm32] use only three wires to drive LCD1602 LCD
- 抽象类中子类与父类
- 研发效能度量指标构成及效能度量方法论
- 定义严苛标准,英特尔Evo 3.0正在加速PC产业升级
猜你喜欢
Appium automation test foundation - appium basic operation API (II)
vulnhub-FirstBlood
obj集合转为实体集合
How difficult is it to pass the certification of Intel Evo 3.0? Yilian technology tells you
List de duplication and count the number
19.[STM32]HC_ SR04 ultrasonic ranging_ Timer mode (OLED display)
Pits encountered in the use of boolean type in development
项目中批量update
Li Kou today's question -729 My schedule I
Appium自动化测试基础 — APPium基础操作API(二)
随机推荐
Go language programming specification combing summary
MySQL overview
The list set is summed up according to a certain attribute of the object, the maximum value, etc
项目中批量update
vulnhub-FirstBlood
abstract关键字和哪些关键字会发生冲突呢
16.[STM32]从原理开始带你了解DS18B20温度传感器-四位数码管显示温度
The computer is busy, and the update is a little slow
Vulnhub-Moneybox
单商户 V4.4,初心未变,实力依旧!
Appium automation test foundation - appium basic operation API (II)
视觉体验全面升级,豪威集团与英特尔Evo 3.0共同加速PC产业变革
Use of RLOCK lock
MySQL giant pit: update updates should be judged with caution by affecting the number of rows!!!
Cs231n notes (medium) -- applicable to 0 Foundation
六种常用事务解决方案,你方唱罢,我登场(没有最好只有更好)
Nine hours, nine people, nine doors problem solving Report
19.[STM32]HC_ SR04 ultrasonic ranging_ Timer mode (OLED display)
I'm fat, huh
Detailed explanation of C language branch statements