当前位置:网站首页>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();
边栏推荐
- Practical operation of vim
- golang xxx. Go code template
- IPv6 transition technology-6to4 manual tunnel configuration experiment -- Kuige of Shangwen network
- [daily question] dichotomy - find a single dog (Bushi)
- JMeter starts from zero (III) -- simple use of regular expressions
- Arduino application development - LCD display GIF dynamic diagram
- Causal AI, a new paradigm for industrial upgrading of the next generation of credible AI?
- CVPR 2022 | Dalian Technology propose un cadre d'éclairage auto - étalonné pour l'amélioration de l'image de faible luminosité de la scène réelle
- 树莓派如何连接WiFi
- 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?
猜你喜欢

300+篇文献!一文详解基于Transformer的多模态学习最新进展

Arduino application development - LCD display GIF dynamic diagram

Nat. Comm. | use tensor cell2cell to deconvolute cell communication with environmental awareness

CVPR 2022 | Dalian Technology propose un cadre d'éclairage auto - étalonné pour l'amélioration de l'image de faible luminosité de la scène réelle

"Final review" 16/32-bit microprocessor (8086) basic register

Bisher - based on SSM pet adoption center

学会pytorch能干什么?

2022-07-02: what is the output of the following go language code? A: Compilation error; B:Panic; C:NaN。 package main import “fmt“ func main() { var a =

leetcode:297. 二叉树的序列化与反序列化
![[graduation season · aggressive technology Er] Confessions of workers](/img/ec/4f4d96e22a1029074b07ab80bfa1d9.png)
[graduation season · aggressive technology Er] Confessions of workers
随机推荐
CVPR 2022 | 大连理工提出自校准照明框架,用于现实场景的微光图像增强
[no title] 2022 chlorination process examination content and free chlorination process examination questions
2022 tea master (intermediate) examination questions and analysis and tea master (intermediate) practical examination video
基于Pytorch和RDKit的QSAR模型建立脚本
Mila, University of Ottawa | molecular geometry pre training with Se (3) invariant denoising distance matching
Arduino application development - LCD display GIF dynamic diagram
MPLS setup experiment
Without sxid, suid & sgid will be in danger- Shangwen network xUP Nange
300+篇文献!一文详解基于Transformer的多模态学习最新进展
"Designer universe" argument: Data Optimization in the design field is finally reflected in cost, safety and health | chinabrand.com org
2022 beautician (intermediate) new version test questions and beautician (intermediate) certificate examination
CVPR 2022 | Dalian Technology propose un cadre d'éclairage auto - étalonné pour l'amélioration de l'image de faible luminosité de la scène réelle
[Apple Push] IMessage group sending condition document (push certificate) development tool pushnotification
Design and implementation of kubelet garbage collection mechanism to protect nodes from being preempted by containers image GC high threshold
服务器无法远程连接原因分析
CVPR 2022 | 大連理工提出自校准照明框架,用於現實場景的微光圖像增强
有监督预训练!文本生成又一探索!
2022 polymerization process examination questions and polymerization process examination skills
2022 Shandong Province safety officer C certificate examination questions and Shandong Province safety officer C certificate simulation examination question bank
[daily question] dichotomy - find a single dog (Bushi)