当前位置:网站首页>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();
边栏推荐
- Intercept string fixed length to array
- Sklearn data preprocessing
- Analysis of the reason why the server cannot connect remotely
- [brush questions] most elements (super water king problem)
- sklearn数据预处理
- 【刷题篇】 找出第 K 小的数对距离
- Is it better to speculate in the short term or the medium and long term? Comparative analysis of differences
- Export of zip file
- [mathematical logic] predicate logic (predicate logic basic equivalent | eliminate quantifier equivalent | quantifier negative equivalent | quantifier scope contraction expansion equivalent | quantifi
- 2022 tea master (intermediate) examination questions and analysis and tea master (intermediate) practical examination video
猜你喜欢
Is pytorch difficult to learn? How to learn pytorch well?
Role of JS No
Wechat applet + Alibaba IOT platform + Hezhou air724ug build a serverless IOT system (III) -- wechat applet is directly connected to Alibaba IOT platform aliiot
js实现在可视区内,文字图片动画效果
中移物联网OneOS与OneNET入选《2021年物联网示范项目名单》
How to download pytorch? Where can I download pytorch?
Mila、渥太华大学 | 用SE(3)不变去噪距离匹配进行分子几何预训练
在写web项目的时候,文件上传用到了smartupload,用了new string()进行转码,但是在数据库中,还是会出现类似扑克的乱码
pytorch难学吗?如何学好pytorch?
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
随机推荐
2022 mobile crane driver examination registration and mobile crane driver operation examination question bank
pytorch是什么?pytorch是一个软件吗?
nodejs基础:浅聊url和querystring模块
CVPR 2022 | Dalian Institute of technology proposes a self calibration lighting framework for low light level image enhancement of real scenes
竞品分析撰写
Recursion: one dimensional linked lists and arrays
Web session management security issues
What is pytorch? Is pytorch a software?
因果AI,下一代可信AI的产业升级新范式?
JS native common knowledge
Deep dive kotlin synergy (20): build flow
Application of I2C protocol of STM32F103 (read and write EEPROM)
Introduction to eth
300+篇文献!一文详解基于Transformer的多模态学习最新进展
The time has come for the domestic PC system to complete the closed loop and replace the American software and hardware system
深潜Kotlin协程(十九):Flow 概述
Wechat applet + Alibaba IOT platform + Hezhou air724ug build a serverless IOT system (III) -- wechat applet is directly connected to Alibaba IOT platform aliiot
阿洛对自己的思考
pytorch怎么下载?pytorch在哪里下载?
xrandr修改分辨率与刷新率