当前位置:网站首页>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();
边栏推荐
- 2022 electrician (Advanced) examination papers and electrician (Advanced) examination skills
- 阿洛对自己的思考
- How to execute a swift for in loop in one step- How can I do a Swift for-in loop with a step?
- Introduction to eth
- Social phobia of contemporary young people (II)
- How does the pytorch project run?
- 深潜Kotlin协程(十九):Flow 概述
- 300+ documents! This article explains the latest progress of multimodal learning based on transformer
- x Problem B
- In Net 6 project using startup cs
猜你喜欢

深潜Kotlin协程(十九):Flow 概述

CEPH Shangwen network xUP Nange that releases the power of data

IPv6 transition technology-6to4 manual tunnel configuration experiment -- Kuige of Shangwen network

Is it better to speculate in the short term or the medium and long term? Comparative analysis of differences

Application of I2C protocol of STM32F103 (read and write EEPROM)

How does the pytorch project run?
![[NLP]—sparse neural network最新工作简述](/img/65/35ae0137f4030bdb2b0ab9acd85e16.png)
[NLP]—sparse neural network最新工作简述

Arduino application development - LCD display GIF dynamic diagram

学会pytorch能干什么?

js实现在可视区内,文字图片动画效果
随机推荐
Social phobia of contemporary young people (III)
Use of sigaction
Mila、渥太华大学 | 用SE(3)不变去噪距离匹配进行分子几何预训练
学会pytorch能干什么?
Supervised pre training! Another exploration of text generation!
How does the pytorch project run?
Half of 2022 is over, so we must hurry up
Analysis of the reason why the server cannot connect remotely
Nat. Comm. | 使用Tensor-cell2cell对细胞通讯进行环境感知去卷积
[brush questions] most elements (super water king problem)
Idea shortcut keys
pytorch是什么?pytorch是一个软件吗?
Social phobia of contemporary young people (II)
pytorch开源吗?
Wechat applet + Alibaba IOT platform + Hezhou air724ug build a serverless IOT system (III) -- wechat applet is directly connected to Alibaba IOT platform aliiot
Error c2694 "void logger:: log (nvinfer1:: ilogger:: severity, const char *)": rewrite the restrictive exception specification of virtual functions than base class virtual member functions
2022 tea master (intermediate) examination questions and analysis and tea master (intermediate) practical examination video
[Apple Push] IMessage group sending condition document (push certificate) development tool pushnotification
"Designer universe" argument: Data Optimization in the design field is finally reflected in cost, safety and health | chinabrand.com org
2022 Shandong Province safety officer C certificate examination questions and Shandong Province safety officer C certificate simulation examination question bank