当前位置:网站首页>[ecmascript6] class
[ecmascript6] class
2022-07-28 14:18:00 【Willard Leozi】
One 、 class Class The concept of
1.1 Basic concepts
Class yes ES6 A grammar sugar in , The bottom layer is still constructor , So most of the functions it realizes ES5 All can be done , however Class It can make the writing of object prototype clearer , It's more like the syntax of object-oriented programming .
The following is through the constructor and class Comparative writing of creating instances :
// The way the constructor works
function Phone(brand, price) {
this.brand = brand
this.price = price
}
Phone.prototype.call = function() {
console.log('call me')
}
let huawei = new Phone(' Huawei ', 2999)
huawei.call()
console.log(huawei)
// class The way
class CPhone {
constructor(brand, price) {
this.brand = brand
this.price = price
}
call() {
console.log('call me')
}
}
let onePlus = new CPhone('1+', 1234)
onePlus.call()
console.log(onePlus)
class Medium constructor It's the construction method , Among them this Point to the instance object of the class .
The data type of the class is a function , The class itself points to the constructor .
All methods of a class are defined in the prototype Attribute above :
class A {
constructor() {
}
toString() {
}
toValue() {
}
}
// The code above is equivalent to the code below
function A () {
// constructor
};
A.prototype.toString = function() {
};
A.prototype.toValue = function() {
};
Calling a method on an instance of a class is equivalent to calling a method on a class prototype :
let a = new A();
a.constructor === A.prototype.constructor
1.2 class Medium constructor
constructor Method is the default method of a class , adopt new When the command generates an object instance , Call this method automatically . A class must have constructor Method , If not explicitly defined , An empty one constructor Method will be added by default .
class A {
}
// Equate to
class A {
constructor() {
}
}
constructor Method returns an instance object by default ( namely this), You can specify to return another object .
class A {
constructor() {
return Object.create(null);
}
}
console.log((new A()) instanceof A);
// false
Be careful :
- The properties of the instance are defined in itself ( namely this On the object ), Otherwise, it's all defined in the prototype ( namely class On )
- class Declare that there is no variable promotion
- If there is a this, By default, it points to an instance of the class
Two 、Class Static members in
The class is the stereotype of the instance , All methods defined in the class , Will be inherited by the instance . If it's before a method , add static keyword , Means that the method will not be inherited by the instance , It's called directly from the class , This is called a " Static members ".
Constructors and class Differences in the writing of static members in :
// Static members in constructors
function Phone() {
}
Phone.name = 'phone'
Phone.change = function() {
console.log('ccccc')
}
Phone.prototype.size = '5.8inch'
let nokia = new Phone()
console.log(nokia.name) // undefined
// nokia.change() // erorr
console.log(nokia.size) // 5.8inch
// class Static members in
class CPhone {
static name = 'phone'
static change() {
console.log('ccccc')
}
size = '5.8inch'
}
let nokia1 = new CPhone()
console.log(nokia1.name) // undefined
// nokia.change() // erorr
console.log(nokia1.size) // 5.8inch
If the static method contains this keyword , This this Refers to the class , Not an instance .
class A {
static classMethod() {
this.baz();
}
static baz() {
console.log('hello');
}
baz() {
console.log('world');
}
}
A.classMethod();
// hello
Static methods classMethod Called this.baz, there this refer to A class , instead of A Example , Equivalent to calling A.baz. in addition , You can also see from this example that , Static methods can be renamed with non-static methods .
Static methods of the parent class , It can be inherited by subclasses .
class A {
static classMethod() {
console.log('hello');
}
}
class B extends A {
}
B.classMethod() // 'hello'
3、 ... and 、Class Inheritance in
The following code passes the constructor and class The way to achieve inheritance :
// The way the constructor works
function Phone(brand, price) {
this.brand = brand
this.price = price
}
Phone.prototype.call = function() {
console.log(' Make a phone call ')
}
function SmartPhone(brand, price, color, size) {
Phone.call(this, brand, price)
this.color = color
this.size = size
}
SmartPhone.prototype = new Phone()
SmartPhone.prototype.constructor = SmartPhone
SmartPhone.prototype.photo = function() {
console.log(' Taking pictures ')
}
SmartPhone.prototype.playGame = function() {
console.log(' Play a game ')
}
const cuizi = new SmartPhone(' Cui Zi ', 2222, 'black', '6.0inch')
console.log(cuizi)
// class Inheritance in
class Phone{
constructor(brand, price) {
this.brand = brand
this.price = price
}
call() {
console.log(' Make a phone call ')
}
}
class SmartPhone extends Phone {
constructor(brand, price, color, size) {
super(brand, price)
this.color = color
this.size = size
}
photo() {
console.log(' Taking pictures ')
}
playGame() {
console.log(' Play the game ')
}
}
const xiaomi = new SmartPhone(' millet ', 799, 'white', '5.8inch')
console.log(xiaomi)
It is worth noting that , Subclasses must be constructor Call in super Method , Otherwise, the newly created instance will report an error , This is because of the subclass itself this The object must be shaped by the parent constructor , So as to get the same instance properties and methods as the parent class , It is then processed ( Plus the unique instance properties and methods of subclasses ), If you don't call super Subclasses don't get this object .
class Animal {
/* ... */ }
class Cat extends Animal {
constructor() {
}
}
let cp = new Cat();
// ReferenceError
Another thing to note ,es5 The constructor can access before calling the parent constructor this, however es6 The constructor of is calling the constructor of the parent class (super) Cannot access before this object .
class A {
constructor(x, y) {
this.x = x;
this.y = y;
}
}
class B extends A {
constructor(x, y, name) {
this.name = name; // ReferenceError
super(x, y);
this.name = name; // correct
}
}
If the subclass is not explicitly defined constructor Method , This method will be added by default .
class Cat extends Animal {
}
// Equate to
class Cat extends Animal {
constructor(...args) {
super(...args);
}
}
Besides , The static method of the parent class will also be inherited by the child class .
class A {
static hello() {
console.log('hello world');
}
}
class B extends A {
}
B.hello() // hello world
Four 、Class Medium super
super stay class Can be used as a function call , It can also be used as an object .
4.1 super Call as function
super When called as a function , Represents the constructor of the parent class .
class A {
}
class B extends A {
constructor() {
super();
}
}
super Although it represents the parent class A Constructor for , But it returns a subclass B Example , namely super Inside this refer to B Example , therefore super() In this case A.prototype.constructor.call(this).
class A {
constructor() {
// new.target Point to the function being executed
console.log(new.target.name);
}
}
class B extends A {
constructor() {
super();
}
}
new A() // A
new B() // B
stay super() Execution time , It points to a subclass B Constructor for , Not the parent class A Constructor for . in other words ,super() Inside this Pointing to B.
4.2 super Call... 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 .
4.2.1 super Object is called in a normal function
class A {
p() {
return 2;
}
}
class B extends A {
constructor() {
super();
console.log(super.p()); // 2
}
}
let b = new B();
In the above code , Subclass B In the middle of super.p() take super Used as an object . At this time ,super In the ordinary way , Point to A.prototype, therefore super.p() Equivalent to A.prototype.p().
Here we need to pay attention to , because super Points to the prototype object of the parent class , So a method or property is defined on a parent class instance , No way super Called .
class A {
constructor() {
this.p = 2;
}
}
class B extends A {
get m() {
return super.p;
}
}
let b = new B();
b.m // undefined
In the above code ,p Parent class A Properties of instances ,super.p You can't quote it . If the attribute is defined on the prototype object of the parent class ,super You can get it .
class A {
}
A.prototype.x = 2;
class B extends A {
constructor() {
super();
console.log(super.x) // 2
}
}
let b = new B();
4.2.2 super Object is called in a static method
Used in static methods , At this time super Will point to the parent class , Not the prototype object of the parent class .
class Parent {
static myMethod(msg) {
console.log('static', msg);
}
myMethod(msg) {
console.log('instance', msg);
}
}
class Child extends Parent {
static myMethod(msg) {
super.myMethod(msg);
}
myMethod(msg) {
super.myMethod(msg);
}
}
Child.myMethod(1); // static 1
const child = new Child();
child.myMethod(2); // instance 2
In the above code ,super Point to the parent class in a static method , Points to the parent class's prototype object in the normal method .
The other thing to note is that , Passed in the static method of the subclass super When a method of the parent class is called , Method internal this Points to the current subclass , Not an instance of a subclass .
class A {
constructor() {
this.x = 1;
}
static print() {
console.log(this.x);
}
}
class B extends A {
constructor() {
super();
this.x = 2;
}
static m() {
super.print();
}
}
B.x = 3;
B.m() // 3
In the above code , Static methods B.m Inside ,super.print Static methods that point to the parent class . In this method this Pointing to B, instead of B Example .
5、 ... and 、 Subclass's rewriting of parent methods
class Phone{
constructor(brand, price) {
this.brand = brand
this.price = price
}
call() {
console.log(' Make a phone call ')
}
}
class SmartPhone extends Phone {
constructor(brand, price, color, size) {
super(brand, price)
this.color = color
this.size = size
}
call() {
console.log(' visual telephone ')
}
}
const xiaomi = new SmartPhone(' millet ', 799, 'white', '5.8inch')
xiaomi.call() // Video call
6、 ... and 、Class Medium getter and setter
class Phone{
get price() {
console.log('price Property is read ')
return '$30'
}
set price(newPrice) {
console.log('price Property has been modified ')
}
}
let s = new Phone()
console.log(s.price) // price Property is read $30
s.price = 'free' // price Property has been modified
边栏推荐
- [server data recovery] HP StorageWorks series server RAID5 offline data recovery of two disks
- qml 图片预览
- QQ robot configuration record based on nonebot2
- 83. (cesium home) how the cesium example works
- LeetCode 105.从前序与中序遍历序列构造二叉树 && 106.从中序与后序遍历序列构造二叉树
- Literature reading (245) roller
- DXF reading and writing: Chinese description of dimension style group codes
- [lvgl events] Application of events on different components (I)
- How to effectively conduct the review meeting (Part 1)?
- 数据库优化 理解这些就够了
猜你喜欢

Qt5 development from introduction to mastery -- the first overview

Operator3 - design an operator

zabbix分布式

Implementation of StrCmp, strstr, memcpy, memmove

作为一个程序员,如何高效的管理时间?

LeetCode 105.从前序与中序遍历序列构造二叉树 && 106.从中序与后序遍历序列构造二叉树

Install mysql5.7.36 in CentOS

JMeter installation tutorial and login add token

Jmeter安装教程及登录增加token

MySQL development skills - View
随机推荐
【Utils】CookieUtil
MVC模型:日历系统
MySql5.5之后的默认存储引擎为InnoDB。
Jmeter安装教程及登录增加token
牛客多校-Link with Level Edito I-(线性dp)
超好用的手机录屏软件推荐
Leetcode 0143. rearrange linked list
RSA encrypts data with private key and decrypts data with public key (not a signature verification process)
Three cases of thread blocking.
一文读懂如何部署具有外部数据库的高可用 K3s
As a programmer, how to manage time efficiently?
软件测试的发展与定义
Revised version | target detection: speed and accuracy comparison (faster r-cnn, r-fcn, SSD, FPN, retinanet and yolov3)
IP black and white list
LeetCode 1331.数组序号转换
UFIDA BiP CRM new product launch enables large and medium-sized enterprises to grow their marketing
Chapter 6 support vector machine
每日一题——奖学金
目标检测:速度和准确性比较(Fater R-CNN,R-FCN,SSD,FPN,RetinaNet和YOLOv3)
Clickhouse架构与设计