当前位置:网站首页>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();
边栏推荐
- Wechat applet + Alibaba IOT platform + Hezhou air724ug built with server version system analysis
- Without sxid, suid & sgid will be in danger- Shangwen network xUP Nange
- Interface embedded in golang struct
- [mathematical logic] predicate logic (first-order predicate logic formula | example)
- Deep dive kotlin synergy (20): build flow
- 有监督预训练!文本生成又一探索!
- 【刷题篇】多数元素(超级水王问题)
- DAPP for getting started with eth
- 错误 C2694 “void Logger::log(nvinfer1::ILogger::Severity,const char *)”: 重写虚函数的限制性异常规范比基类虚成员函数
- SAP UI5 应用开发教程之一百零五 - SAP UI5 Master-Detail 布局模式的联动效果实现明细介绍
猜你喜欢

Role of JS No

pytorch开源吗?

Without sxid, suid & sgid will be in danger- Shangwen network xUP Nange

2022 polymerization process examination questions and polymerization process examination skills

Bisher - based on SSM pet adoption center

竞品分析撰写

Web session management security issues

pytorch怎么下载?pytorch在哪里下载?

Daily question - ugly number

SAP UI5 应用开发教程之一百零五 - SAP UI5 Master-Detail 布局模式的联动效果实现明细介绍
随机推荐
IPv6 foundation construction experiment
[Apple Photo Album push] IMessage group anchor local push
Recursion: one dimensional linked lists and arrays
Nat. Comm. | 使用Tensor-cell2cell对细胞通讯进行环境感知去卷积
[Yu Yue education] reference materials of political communication science of Communication University of China
2022-07-02:以下go语言代码输出什么?A:编译错误;B:Panic;C:NaN。 package main import “fmt“ func main() { var a =
SAP UI5 应用开发教程之一百零五 - SAP UI5 Master-Detail 布局模式的联动效果实现明细介绍
Application of I2C protocol of STM32F103 (read and write EEPROM)
[brush questions] connected with rainwater (one dimension)
Wechat applet + Alibaba IOT platform + Hezhou air724ug built with server version system analysis
服务器无法远程连接原因分析
Arduino application development - LCD display GIF dynamic diagram
2022年已过半,得抓紧
记一次 .NET 差旅管理后台 CPU 爆高分析
学会pytorch能干什么?
Export of zip file
Read a paper_ ChineseBert
[graduation season · aggressive technology Er] Confessions of workers
在 .NET 6 项目中使用 Startup.cs
Is pytorch open source?