当前位置:网站首页>Use ES6 new Target to simulate abstract classes
Use ES6 new Target to simulate abstract classes
2022-06-23 02:56:00 【It workers】
lately , We found that symbol Is the only value , but symbol Cannot be new operation , Can only be used as a function , function new Type error occurs when
new Symbol()
// error
Uncaught TypeError: Symbol is not a constructor
at new Symbol (<anonymous>)
at <anonymous>:1:1If the underlying implementation is not considered , Is it possible to implement a function that can only be called but cannot be called at the code level ? After thinking , Write the following code :
function disConstructor() {
if (this !== window) {
throw new TypeError(' disConstructor is not a constructor')
}
console.log('gogo go')
}
// The test results are as follows
disConstructor() // gogo go
new disConstructor()
// error
Uncaught TypeError: disConstructor is not a constructor
at new disConstructor (<anonymous>:3:15)
at <anonymous>:1:1Use nodejs when ,window You can switch to global, The execution result of the code remains unchanged . This is because there is no applicable scenario for individuals . therefore , Although no further research , But lately , reread es 6 Found out new.target.
new.target attribute
Introduce ( quote mdn file )
new.target Property allows you to detect whether a function or constructor passes through new Operator is called . Through new Operator is initialized in a function or constructor ,new.target Returns a reference to a constructor or function . In normal function calls ,new.target The value of is undefined.
In this case Our code can be changed to :
function disConstructor() {
// In ordinary function calls ,new.target The value of is undefined.
if (new.target) {
throw new TypeError(' disConstructor is not a constructor')
}
console.log('gogo go')
}Get the same answer as the above code .
thorough
Don't es6 Is the specially added function only used to check our function calling methods ? In the process of consulting, it is found that most of the schemes use new.target Write classes that can only be inherited . Similar to implementation java The abstract class of .
class Animal {
constructor(name, age) {
if (new.target === Animal) {
throw new Error('Animal class can`t instantiate');
}
this.name = name
this.age = age
}
// Other code
...
}
class Dog extends Animal{
constructor(name, age, sex) {
super(name, age)
this.sex = sex
}
}
new Animal()
// error
Uncaught Error: Animal class can`t instantiate
at new Animal (<anonymous>:4:13)
at <anonymous>:1:1
new Dog('mimi', 12, ' Male ')
// Dog {name: "mimi", age: 12, sex: " Male "}however java Abstract classes and abstract methods need to be overridden , There is no plan for this . So in the process of testing and using , However, I accidentally found that the superclass can access the prototype of the derived class during construction , Use it .
class Animal {
constructor(name, age) {
console.log(new.target.prototype)
}
// Other code
...
}The previous run-time call to the method that needs to be rewritten reported an error as follows .
class Animal {
constructor(name, age) {
this.name = name
this.age = age
}
getName () {
throw new Error('please overwrite getName method')
}
}
class Dog extends Animal{
constructor(name, age, sex) {
super(name, age)
this.sex = sex
}
}
const pite = new Dog('pite', 2, ' Male ')
a.getName()
// error
Uncaught Error: please overwrite getName method
at Dog.getName (<anonymous>:8:11)
at <anonymous>:1:3However, at this time new.target , I can use Tectonic period An error is reported when operating on a subclass .
class Animal {
constructor(name, age) {
// If target No Base class And No, getName Report errors
if (new.target !== Animal && !new.target.prototype.hasOwnProperty('getName')) {
throw new Error('please overwrite getName method')
}
this.name = name
this.age = age
}
}
class Dog extends Animal{
constructor(name, age, sex) {
super(name, age)
this.sex = sex
}
}
const pite = new Dog('pite', 2, ' Male ')
// error
Uncaught Error: please overwrite getName method
at new Animal (<anonymous>:5:13)
at new Dog (<anonymous>:14:5)
at <anonymous>:1:1At this point, you can advance the errors that occur when running the method to the construction time , Although they are all in operation , But the error trigger mechanism should be early and harmful . Instead, it is a kind of protection for the code .
Yes, of course , Using superclasses to access the prototypes of derived classes during construction is far from simple , It must be very powerful , You can talk about understanding and role in combination with business scenarios .
边栏推荐
- Call rest port to implement nailing notification
- Summary of easy-to-use MySQL interview questions (Part 1)
- Wechat applet camera compressed image is Base64
- Learning notes of recommendation system (1) - Collaborative Filtering - Theory
- Operate attribute chestnut through reflection
- What is sitelock? What is the function?
- What if the software gets stuck and cannot end the process?
- [data preparation and Feature Engineering] data cleaning
- Docker builds redis3 master-slave cluster and expands the capacity
- Vs code remote SSH configuration
猜你喜欢

8. greed

6. template for integer and real number dichotomy

Log a log4j2 vulnerability handling

C language series - Section 4 - arrays

Xgboost principle
What is sitelock? What is the function?

Soft exam information system project manager_ Contract Law_ Copyright_ Implementation Regulations - Senior Information System Project Manager of soft exam 030

Soft exam information system project manager_ Information system comprehensive testing and management - Senior Information System Project Manager of soft test 027

Vulnhub DC-5

Xgboost Guide
随机推荐
Calling applet demo modifying the default large screen view
Reinforcement learning series (IV) -policygradient example
Applet control version update best practices
Goframe framework (RK boot): fast implementation of CSRF verification
Essentials of fleet video playback and fleet videoplayer video playback components
Quic implementation in rust --- Quinn
Windows system poisoning, SQL Server database file recovery rescue and OA program file recovery
Problem thinking and analysis process
SQLSERVER database restore stored procedure script
How to make traditional Chinese medicine labels with pictures
Apache Druid's engineering practice in shopee
No error is reported when using the Gorm framework to create a table, but the data cannot be inserted successfully
Salesforce file (II) custom development fileUpload
Implementation idea and solution of calling global monitoring for applet
Xgboost Guide
[target tracking] open source | polytrack: use boundary polygons to quickly track and segment multiple targets, instead of bounding box and mask tracking
Soft exam information system project manager_ Contract Law_ Copyright_ Implementation Regulations - Senior Information System Project Manager of soft exam 030
862. triple sorting
January 31, 2022: Maze III. There is a ball in the maze of open spaces and walls. ball
How to generate IATA barcode in batch through TXT file