当前位置:网站首页>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);边栏推荐
- CASS11.0.0.4 for AutoCAD2010-2023免狗使用方法
- Introduction to the official functions of easyrecovery14 data recovery software
- Basic statement of MySQL (1) - add, delete, modify and query
- 银行业客户体验管理现状与优化策略分析
- About the new features of ES6
- 如何让最小 API 绑定查询字符串中的数组
- MangoDB
- CentOS上使用Docker安装和部署Redis
- Summary of APP launch in vivo application market
- Shell programming specifications and variables
猜你喜欢

DNA科研实验应用|环糊精修饰核酸CD-RNA/DNA|环糊精核酸探针/量子点核酸探针

【12】 Understand the circuit: from telegraph to gate circuit, how can we "send messages from thousands of miles"?

The vscode run command reported an error: the mark "&" is not a valid statement separator in this version.

Vscode connection remote server development

EasyRecovery14数据恢复软件官方功能简介

客户案例 | 聚焦流程体验,助银行企业APP迭代

New features of ES6 (2)

PNA modified polypeptide arms PNA PNA DNA suc aapf PNA suc - (ALA) 3 PNA

O2O电商线上线下一体化模式分析

DNA coupled PbSe quantum dots | near infrared lead selenide PbSe quantum dots modified DNA | PbSe DNA QDs
随机推荐
What is the reason why dragging the timeline is invalid when playing device videos on the easycvr platform?
What is the reason why the channel list is empty on the intelligent security video platform easycvr?
大疆livox定制的格式CustomMsg格式转换pointcloud2
Bert and RESNET can also be trained on mobile phones?!
PNA修饰多肽ARMS-PNA|PNA-DNA|suc-AAPF-pNA|Suc-(Ala)3-pNA
最新!国资委发布国有企业数字化转型新举措
MangoDB
Linux Installation and uninstallation of MySQL
Boostrap
Some problems about too fast s verification code
OpenGL development with QT (I) drawing plane graphics
CdS quantum dots modified DNA | CDs DNA QDs | near infrared CdS quantum dots coupled DNA specification information
How can chrome quickly transfer a group of web pages (tabs) to another device (computer)
TS学习(八) :TS中的类
关于ES6的新特性
New features of ES6 (2)
EasyRecovery14数据恢复软件官方功能简介
PNA肽核酸修饰多肽Suc-Tyr-Leu-Val-pNA|Suc-Ala-Pro-Phe-pNA 11
VIVO应用市场APP上架总结
采用QT进行OpenGL开发(一)绘制平面图形