当前位置:网站首页>TS learning (VIII): classes in TS
TS learning (VIII): classes in TS
2022-07-27 07:06:00 【Snail at the bottom of the well】
TS Chinese Writing
before js Chinese calligraphy is like this , Then we add TS You will find that the error is reported
class User {
constructor(name:string,age:number) {
this.name=name;
this.age=age;
}
}
Why? ? stay TS He thinks it's not very good for you to write code like this , Because in TS Hit you User After this class is written ,
What are the properties and methods in it , You should know clearly , therefore TS Think you should write these attributes in one place ,
Instead of using constructors constructor Create data dynamically , stay js You can use constructors to dynamically add data ,
And in the TS Is not allowed in ,TS It is considered that adding attributes to an object is not allowed after creating an object ,
Due to the dynamic addition of attributes , There may be some hidden dangers , therefore TS We are not allowed to add attributes dynamically
const obj = {}
obj.name=' Snail ';
obj.age=18;
Knowledge supplement
stay TS It's impossible to do this , Someone might say because const reason , I can only say, young man, you are still young ,js The foundation is not solid ,
const I usually define constants , It's something fixed, such as a status code , Such as const STATUS=200,
Like this, Put it in the configuration file , Import when using ,const Say that the defined value cannot be changed , It's actually a memory address
The memory address of the basic data type will not change , And the reference data type , The memory address will change , Why can it still be used here const
That's because const What cannot be changed is the name of the reference data type , The address can be changed , such as const room 1={}, Define a room
Name is ” room 1“, Although I can add and delete things to the room , But the name of the room has not changed , Can I change the name of the other room to ” room 1“,
Just the address changed , But the name hasn't changed , So this is the truth
The knowledge points are supplemented , continue TS, since TS It is not allowed to add attributes dynamically, so how to write it
Use Attribute list to describe Properties in a class , What do you mean , Take up a
class User {
name:string
age:number
constructor(name: string, age: number) {
this.name=name;
this.age=age;
}
}
const u= new User(" Snail ",18);
// Cannot add attribute
u.sex=" male "// There will be a mistake here
// You can also assign values like this
const u= new User();
u.name=" Snail ",18
u.age=18
Write the attribute in the class , Indicates that there are these attributes in this class , Only these attributes can be used later , Can not add , Otherwise, an error will be reported
It seems a little uncomfortable to think of this here , In case I have many attributes , That's not to write a pile , I feel so troublesome
Property initialization check
Sometimes we may forget to assign values to objects , Such as : There is no age assignment
class User {
name:string
age:number
constructor(name: string, age: number) {
this.name=name;
}
}
const u= new User(" Snail ",18);
But he won't make a mistake , But some properties we have to assign , What to do at this time
Here we need to use a configuration strictPropertyInitialization, More strictly check whether the attribute is initialized , It will check whether the attribute is assigned
{
"compilerOptions": {
"target": "es2016",// Configure the version standard for compiling the target code
"module": "commonjs",// Configure the modularity standard used by the compilation target
"lib": ["es2016"], // Indicates the default details ts Which environment is used
"outDir": "./dist",// Directory of compilation results
"strictNullChecks": true,//TS Check whether the variable is null
"removeComments": true,/* Whether comments are included in the compilation results */
"noImplicitUseStrict": true,/* Whether there is... In the compilation result "use strict"*/
"esModuleInterop": true,// Enable es Modular interactive non es Module export
"strictPropertyInitialization": true,// More strictly check whether the attribute is initialized
},
"include":["./src"],// perform ts The catalog of
}
With this configuration , The constructor above does not give age assignment ,TS Will prompt age Property error , We have to assign values to attributes
Property defaults
Of course, we can also set default values for attributes , For example, the default gender is ” male “, There are two approaches
Method 1, Constructor parameter default method , This is creating user The object can be the default male , If you want to modify , be
const u= new User(" Snail ",18," Woman "), That's itclass User { name:string age:number gender: " male " | " Woman " constructor(name: string, age: number,gender:" male " | " Woman " = " male ") { this.name=name; this.age=age; this.gender=gender; } }Method 2, Attribute default method , Default values are given when defining attributes , Defining attributes gender when , The default value is male , In this way, there is no need to assign a value to this attribute in the constructor ,
So here's a problem , Since there is no assignment of this attribute in the constructor , How to modify this attribute , If you want to be in
const u= new User(" Snail ",18," Woman ")Add a parameter to it , You will find it useless ,Because constructors don't have this parameter , There is no addition , The right way , Use object [ attribute ]="XX"; The way to modify , Such as u.gender=" Woman "; So you can change the value
class User { name:string age:number gender: " male " | " Woman " = " male " constructor(name: string, age: number) { this.name=name; this.age=age; } }
Attribute optional value
When the generic type can have value or not transmit , For example, when our ID number can be filled in or not , How to assign values to attributes , The two methods
Method 1、 “|” Symbol IDCard:string | undefined = undefined, This way of writing
class User { IDCard: string | undefined =undefined; constructor() { } }Method 2、 Chain operation IDCard?: string, image js The chain operation in is the same
class User { IDCard?: string constructor() { } }
Read-only property
When a property cannot be changed after it is created , Then this attribute cannot be modified later , Then we have to use readonly, With this added , It cannot be modified later
class User {
readonly uid:number
constructor() {
this.uid=new Date().getTime()
}
}
const u= new User();
// I want to modify it here , The result cannot be modified , Report errors
u.uid=1
Access modifier , You can control the access rights of a member in the class
public: Default access modifier , Open , All code is accessible
private: Private modifier , Only in classes can you access
class User { readonly uid:number name:string age:number gender: " male " | " Woman " =" male " IDCard?: string private money:number = 1000000// This is my own money , I don't want to visit outside , Make changes useMoney: number =0// Use money and earn money constructor(name: string, age: number) { this.uid=new Date().getTime() this.name=name; this.age=age; } makeMoney(){ this.money +=this.useMoney console.log(" The remaining amount "+this.money) } } const u= new User(" Snail ",18); u.useMoney=1000// To earn money u.makeMoney()// Check how much money is leftAdd : stay js To realize private in, you can use Symble; Of course, these modifiers can also be used in methods , In this way, private methods cannot be called outside
class User { private money:number = 1000000// This is my own money , I don't want to visit outside , Make changes useMoney: number =0// Use money and earn money constructor() { } private makeMoney(){ this.money +=this.useMoney console.log(" The remaining amount "+this.money) } } const u= new User(); u.makeMoney()// There will be a mistake here , It is forbidden to call this method
Add
We write like this , Directly assign values to attributes in the constructor , I didn't do anything , This seems too mechanized , trouble ,
class User {
name:string
age:number
constructor(name: string, age: number) {
this.name=name;
this.age=age;
}
}
TS Gave us a grammar candy , When an attribute is in the constructor , Assign values to attributes directly without any operation , It can be abbreviated as , as follows , This is the same as the above writing
This way of writing Yes and only if , Attributes are passed through the parameters of the constructor , And assign to this attribute without any processing , Can be abbreviated
class User2 {
constructor(public name: string,public age: number) {}
}
const u2=new User2(" Chloe ",18)
console.log(u2);边栏推荐
- Account management and authority
- 基于SSM图书借阅管理系统
- DNA(脱氧核糖核酸)供应|碳纳米管载核酸-DNA/RNA材料|DNA/RNA核酸修饰磁性纳米颗粒
- VIVO应用市场APP上架总结
- Cass11.0.0.4 for autocad2010-2023 dog free usage
- 手机上也能训练BERT和ResNet了?!
- ES6的新特性(2)
- 运行代码报错: libboost_filesystem.so.1.58.0: cannot open shared object file: No such file or directory
- Dsgan degenerate network
- Interpretation of deepsort source code (III)
猜你喜欢

DNA modified near infrared two region GaAs quantum dots | GaAs DNA QDs | DNA modified GaAs quantum dots

After adding a camera (camera) to the UAV in gazebo, the UAV cannot take off

Express接收请求参数

Talk about multimodality of fire

Speech and language processing (3rd ed. draft) Chapter 2 - regular expression, text normalization, editing distance reading notes

EasyCVR设备管理列表页面搜索时,分页数据不显示的问题修复

Shell programming specifications and variables

How can chrome quickly transfer a group of web pages (tabs) to another device (computer)

聊聊大火的多模态

DNA(脱氧核糖核酸)供应|碳纳米管载核酸-DNA/RNA材料|DNA/RNA核酸修饰磁性纳米颗粒
随机推荐
Basic statement of MySQL (1) - add, delete, modify and query
工控用Web组态软件比组态软件更高效
ES6 new features (getting started)
Problems related to compilation and training of Darknet yolov3 and Yolo fast using CUDA environment of rtx30 Series graphics card on win10 platform
Shell编程的规范和变量
Event capture and bubbling - what is the difference between them?
Analysis of online and offline integration mode of o2o E-commerce
PNA肽核酸修饰多肽Suc-Tyr-Leu-Val-pNA|Suc-Ala-Pro-Phe-pNA 11
CdS quantum dots modified DNA | CDs DNA QDs | near infrared CdS quantum dots coupled DNA specification information
程序、进程、线程、协程以及单线程、多线程基本概念
Qi Yue: thiol modified oligodna | DNA modified cdte/cds core-shell quantum dots | DNA coupled indium arsenide InAs quantum dots InAs DNA QDs
网易云信亮相 GIAC 全球互联网架构大会,解密新一代音视频架构在元宇宙场景的实践...
正则表达式
deepsort源码解读(七)
VIVO应用市场APP上架总结
基于SSM音乐网站管理系统
CentOS上使用Docker安装和部署Redis
采用QT进行OpenGL开发(一)绘制平面图形
Livox Slam (with lio+ closed loop detection optimization)
基于SSM医院预约管理系统