当前位置:网站首页>Classes in TS
Classes in TS
2022-07-03 04:08:00 【Next to the left hand is the right hand】
ts Class in
Classes can be understood as templates , Objects can be instantiated through templates
ts Basic use and inheritance of classes in
class Idol {
name: string;
age: number;
gender: string;
constructor(
name: string = "justin",
age: number = 20,
gender: string = "male"
) {
// Update the properties in the object
this.name = name;
this.age = age;
this.gender = gender;
}
skill(str: string = "singing") {
console.log(`i am ${this.name},i can ${str}`);
}
}
const defaultPerson = new Idol();
defaultPerson.skill();
// Class inheritance
class Student extends Idol {
constructor(name: string, age: number, gender: string) {
// Call the constructor in the parent class
super(name, age, gender);
}
greet() {
console.log(" I am a student , It's also idol Words of ");
super.skill("dance");
}
skill() {
console.log(" Override methods in the parent class ");
}
}
const student = new Student("Ari", 18, "female");
student.greet();
If there is an inheritance relationship between classes , Use extends keyword , Subclasses can call constructors in the parent class , It uses super keyword , Including the parent class calling ordinary methods in the parent class , You can also use extend, A class can override the method of its parent class
If B Class inheritance A class
A---- Base class 、 Parent class
B---- Subclass 、 Derived class
Polymorphism in class
Definition : The reference of the parent type points to the object of the child type , Different types of objects target the same method , There are different behaviors
class Father {
name: string;
constructor(name: string) {
this.name = name;
}
getHeight(h: number = 170) {
console.log(`${this.name} Height is ${h}`);
}
}
class Son extends Father {
constructor(name: string) {
super(name);
}
// Override methods in the parent class
getHeight(h: number = 180) {
console.log(`${this.name} It's the son , Height is ${h}`);
}
}
class Daugther extends Father {
constructor(name: string) {
super(name);
}
getHeight(h: number = 165) {
console.log(`${this.name} It's a daughter , Height is ${h}`);
}
}
const father: Father = new Father(" Zhang San ");
father.getHeight(); // Zhang San is 170
const son: Son = new Son(" Zhang Sanfeng ");
son.getHeight(); // Zhang Sanfeng is a son , Height is 180
const daugther: Daugther = new Daugther(" Wu Hua Zhang ");
daugther.getHeight(); // Zhangwuhua is a daughter , Height is 165
// Use a parent class to qualify subclasses
const son2: Father = new Son(" zhang wuji ");
son2.getHeight(); // Zhang Wuji is a son , Height is 180
const daugther2: Father = new Daugther(" Zhang Ziyi ");
daugther2.getHeight(); // Zhang Ziyi is a daughter , Height is 165
// The same method was called , Produced different results
function getPersonHeight(person: Father) {
person.getHeight();
}
getPersonHeight(son); // Zhang Sanfeng is a son , Height is 180
getPersonHeight(daugther); // Zhangwuhua is a daughter , Height is 165
Class modifier
1>public Modifier Default modifier , Any location can access
2>private Modifier Only internal access , external ( Instance object ) And words are not accessible
3>protected Modifier external ( Instance object ) cannot access , But it can be accessed inside and in the word class
class Dad {
// public name: string;
// private name: string;
protected name: string;
constructor(str: string) {
this.name = str;
}
introduce() {
console.log(` Hello , I am a ${this.name}`);
}
}
class Son extends Dad {
constructor(uname: string) {
super(uname);
}
eat() {
console.log(`${this.name} What to eat `);
}
}
const dad = new Dad(" Zhang Sanfeng ");
console.log(dad.name);
const son = new Son(" Zhang Sanfan ");
console.log(son.name);
Constructor parameters use public private protected r modification , Then the corresponding attributes are automatically added to this class ; And whether it is accessible is the same as above
4>readonly Modifier
// readonly It's a keyword , For attributes in the class To embellish , After modification , The attribute member cannot be modified at will
// In the constructor , You can modify the read-only attribute member data
class Person {
readonly name: string; // As long as there is readonly, Then only the constructor can modify it
constructor(name: string) {
// The read-only attribute data can be modified in the constructor
this.name = name;
}
greet() {
console.log(this.name);
// Common methods in class , It cannot be modified readonly Attribute values of members
// this.name = " Wang Wu ";
}
}
const person = new Person(" Zhang San ");
// Read only properties cannot be modified outside
// person.name = " Li Si ";
console.log(person.name);
Use modifiers to modify the parameters of the constructor
class Person {
// name: string;
constructor(readonly name: string = " Zhao Liu ") {
// this.name = name;
// Used in constructor parameters readonly modification , Then a corresponding member attribute will be automatically added to this class
console.log(this.name);
}
greet() {
console.log(this.name);
// The parameters in the constructor are decorated , It can't be modified ,
// this.name = " Wang Wu ";
}
}
const person = new Person(" Zhang San ");
// The parameters in the constructor are decorated , It can't be modified , Will report a mistake
// person.name = " Li Si ";
console.log(person.name);
Constructor parameters use public private protected readonly modification , Then the corresponding attributes are automatically added to this class ; If it is readonly, So read only , Ordinary functions of this class and other external functions cannot be modified
Memory
class Person {
firstName: string;
lastName: string;
constructor(firstName: string, lastName: string) {
this.firstName = firstName;
this.lastName = lastName;
}
get fullName() {
console.log("get in ...");
return this.firstName + this.lastName;
}
set fullName(newName: string) {
console.log("set in ...");
const temp = newName.split("_");
this.firstName = temp[0];
this.lastName = temp[1];
}
}
const person = new Person(" The east ", " Invincible ");
console.log(person.fullName);
// If only get, No, set, that fullName It's a read-only property , If it is modified, an error will be reported
person.fullName = " Ouyang _ Cici ";
console.log(person);
adopt get visit ; adopt set Setup modification ; If only get Then it is a read-only attribute
Static attribute
Static members : Pass in class static Modifier modifies a property or method
Static members are the same as the Forbidden City class name when used . The syntax of ; Class name . attribute class . Method
Constructor cannot be used static To modify , But ordinary methods in classes are ok
class Person {
static age: number;
// constructor(age: number) {
constructor() {
// here this Is the instance object ,age It's a static property , Cannot call... Through an instance object
// this.age = age;
}
static greet() {
console.log(" Hello everyone ");
}
}
let p: Person = new Person();
// Cannot access through instance objects and instance methods ( Of course, it cannot be modified ) Static properties and static methods
// console.log(p.age);
// p.greet();
// Access internal properties and methods by class name
Person.age = 28;
console.log((Person.age = 60));
Person.greet();
abstract class
Abstract methods have no concrete implementation , Abstract classes cannot be instantiated
We can only let subclasses ( Derived class ) Instantiate and implement methods inside abstract classes
abstract class People {
// abstract communicate(){
// console.log(" Abstract methods cannot have an implementation ");
// };
abstract communicate();
}
// Report errors : Cannot create an instance of an abstract class
// const p=new People()
class Chinese extends People {
communicate() {
console.log(" Speak Chinese ");
}
}
const cn = new Chinese();
cn.communicate();
边栏推荐
- pytorch项目怎么跑?
- Application of I2C protocol of STM32F103 (read and write EEPROM)
- 【毕业季·进击的技术er】职场人的自白
- Role of JS No
- 国产PC系统完成闭环,替代美国软硬件体系的时刻已经到来
- 2022年已过半,得抓紧
- The 10th China Cloud Computing Conference · China Station: looking forward to the trend of science and technology in the next decade
- 300+篇文献!一文详解基于Transformer的多模态学习最新进展
- Design and implementation of kubelet garbage collection mechanism to protect nodes from being preempted by containers image GC high threshold
- [set theory] set concept and relationship (set family | set family examples | multiple sets)
猜你喜欢
![[Apple Photo Album push] IMessage group anchor local push](/img/a7/6a27d646ecba0d7c93f8dac38492a2.jpg)
[Apple Photo Album push] IMessage group anchor local push

『期末复习』16/32位微处理器(8086)基本寄存器

Esp32 series (3): GPIO learning (take simple GPIO input and output, ADC, DAC as examples)

JS实现图片懒加载

用户体验五要素

Daily question - ugly number

300+ documents! This article explains the latest progress of multimodal learning based on transformer

The 10th China Cloud Computing Conference · China Station: looking forward to the trend of science and technology in the next decade
![[home push IMessage] software installation virtual host rental tothebuddy delay](/img/e7/eb20a773e4b674962f856d179a3769.jpg)
[home push IMessage] software installation virtual host rental tothebuddy delay

2022 tea master (intermediate) examination questions and analysis and tea master (intermediate) practical examination video
随机推荐
IPv6 foundation construction experiment
Is it better to speculate in the short term or the medium and long term? Comparative analysis of differences
[learning notes] seckill - seckill project - (11) project summary
[national programming] [software programming - Lecture Video] [zero foundation introduction to practical application]
毕设-基于SSM宠物领养中心
2022 tea master (intermediate) examination questions and analysis and tea master (intermediate) practical examination video
JS realizes lazy loading of pictures
When writing a web project, SmartUpload is used for file upload and new string () is used for transcoding, but in the database, there will still be random codes similar to poker
TCP, the heavyweight guest in tcp/ip model -- Kuige of Shangwen network
C language hashtable/hashset library summary
2022 beautician (intermediate) new version test questions and beautician (intermediate) certificate examination
IPv6 transition technology-6to4 manual tunnel configuration experiment -- Kuige of Shangwen network
Five elements of user experience
阿洛对自己的思考
Wechat applet + Alibaba IOT platform + Hezhou air724ug build a serverless IOT system (III) -- wechat applet is directly connected to Alibaba IOT platform aliiot
[Blue Bridge Road -- bug free code] interpretation of some codes of matrix keyboard
在 .NET 6 项目中使用 Startup.cs
In Net 6 project using startup cs
What is the correct way to compare ntext columns with constant values- What's the right way to compare an NTEXT column with a constant value?
pytorch开源吗?