当前位置:网站首页>Use of typescript classes
Use of typescript classes
2022-07-02 04:41:00 【wendyTan10】
TypeScrip The use of the class
class Basic use of
This article mainly explains typescript The use of classes in , Do not explain the definition of classes too much ;
The basic properties of a class : encapsulation , polymorphic and Inherit ;
Use class Keyword to define a class :
class Person {
name: string
age: number
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
eating() {
console.log(this.name + " eating");
}
}
const p = new Person("wendy", 18)
class Inheritance :extends,super
class Student extends Person {
sno: number
constructor(name: string, age: number, sno: number) {
// super Call the constructor of the parent class
super(name, age);
this.sno = sno;
}
eating() {
console.log("student eating");
super.eating();
}
studying() {
console.log("studying");
}
}
const stu = new Student("why", 18, 111);
console.log(stu.name);
console.log(stu.age);
console.log(stu.sno);
class The polymorphism of
class Animal {
action() {
console.log("animal action")
}
}
class Dog extends Animal {
action() {
console.log("dog running!!!")
}
}
class Fish extends Animal {
action() {
console.log("fish swimming")
}
}
class Person extends Animal {
}
// animal: dog/fish
// The purpose of polymorphism is to write more general code
function makeActions(animals: Animal[]) {
animals.forEach(animal => {
animal.action()
})
}
makeActions([new Dog(), new Fish(), new Person()])
Member modifier
1. Attribute public、private and protected
stay TypeScript in , Class's properties and methods support three modifiers : public、private、protected
publicThe decoration is visible anywhere 、 A public property or method , The default attribute is public Of ;privateThe modification is only visible in the same class 、 A private property or method ;protectedThe modifier is visible only in the class itself and its subclasses 、 A protected property or method ;
public Is the default modifier , Ignore when you don't write public, Let's demonstrate private and protected.
class Person {
private name: string = ""
// It encapsulates two methods , Access... Through methods name
getName() {
return this.name
}
setName(newName) {
this.name = newName
}
}
const p = new Person()
console.log(p.getName())
p.setName("why")
// protected: You can access... Within classes and subclasses
class Person {
protected name: string = "123"
}
class Student extends Person {
getName() {
return this.name
}
}
const stu = new Student()
console.log(stu.getName())
2. Read-only property readonly
If there is a property that we don't want the outside world to modify , Just want to use directly after determining the value , Then you can use readonly:
- Read only properties can be assigned in the constructor , After assignment, it cannot be modified
- The property itself cannot be modified , But if it's an object type , The properties in the object can be modified
class Person {
readonly name: string
age?: number
readonly friend?: Person
constructor(name: string, friend?: Person) {
this.name = name
this.friend = friend
}
}
const p = new Person("why", new Person("kobe"))
console.log(p.name)
console.log(p.friend)
// It can't be modified directly friend
// p.friend = new Person("james")
if (p.friend) {
p.friend.age = 30
}
3.getters/setters
Some private properties cannot be accessed directly , Or some properties we want to listen for (getter) And set up (setter) The process of , At this time, we can use accessors .
class Person {
private _name: string
constructor(name: string) {
this._name = name
}
// accessor setter/getter
// setter
set name(newName) {
this._name = newName
}
// getter
get name() {
return this._name
}
}
const p = new Person("why")
p.name = "coderwhy"
console.log(p.name)
4. Static members
Static members are properties of classes , Instead of the properties of the instance object ;
class Student {
static time: string = "20:00"
static attendClass() {
console.log(" To learn ~")
}
}
let wendy = new Student();
console.log(wendy.name);//undefined
console.log(Student.time)
Student.attendClass()
5. abstract class abstract
Characteristics of abstract classes (abstract):
- With abstract The starting class is an abstract class ;
- Cannot create object ;
- Classes that need to be inherited ; Abstract methods can only be defined in abstract classes , Subclasses must override ;
function makeArea(shape: Shape) {
return shape.getArea()
}
// An abstract class that defines a shape
abstract class Shape {
// Define an abstract method
// Abstract methods to abstract start , There is no method body
// Abstract methods can only be defined in abstract classes , Subclasses must override abstract methods
abstract getArea(): number
}
class Rectangle extends Shape {
private width: number
private height: number
constructor(width: number, height: number) {
super()
this.width = width
this.height = height
}
// Rewrite the method of area calculation
getArea() {
return this.width * this.height
}
}
class Circle extends Shape {
private r: number
constructor(r: number) {
super()
this.r = r
}
// Rewrite the method of area calculation
getArea() {
return this.r * this.r * 3.14
}
}
const rectangle = new Rectangle(20, 30);
const circle = new Circle(10);
console.log(makeArea(rectangle)); // Find the area of a rectangle
console.log(makeArea(circle)); // Find the area of a circle
6. The type of the class
Class itself can also be used as a data type :
class Person {
name: string = "123"
eating() {
}
}
const p = new Person()
const p1: Person = {
name: "why",
eating() {
}
}
function printPerson(p: Person) {
console.log(p.name)
}
printPerson(new Person())
printPerson({
name: "kobe", eating: function() {
}})
边栏推荐
- Virtual machine installation deepin system
- Play with concurrency: draw a thread state transition diagram
- Websites that it people often visit
- Major domestic quantitative trading platforms
- win11安装pytorch-gpu遇到的坑
- 深圳打造全球“鸿蒙欧拉之城”将加快培育生态,优秀项目最高资助 1000 万元
- geotrust ov多域名ssl證書一年兩千一百元包含幾個域名?
- One step implementation of yolox helmet detection (combined with oak intelligent depth camera)
- Arbre binaire pour résoudre le problème (2)
- ThinkPHP kernel work order system source code commercial open source version multi user + multi customer service + SMS + email notification
猜你喜欢

WiFi 5GHz frequency

Unity particle Foundation

Federal learning: dividing non IID samples according to Dirichlet distribution

Ten thousand volumes are known to all, and one page of a book is always relevant. TVP reading club will take you through the reading puzzle!

Win10 disk management compressed volume cannot be started

Analyze the space occupied by the table according to segments, clusters and pages

Deep understanding of lambda expressions

Virtual machine installation deepin system

Landing guide for "prohibit using select * as query field list"

Unit testing classic three questions: what, why, and how?
随机推荐
Embedded-c language-9-makefile/ structure / Consortium
[graduation season · advanced technology Er] young people have dreams, why are they afraid of hesitation
Is it safe to open an account with first venture securities? I like to open an account. How can I open it?
Mysql中常见的锁
DC-1靶场搭建及渗透实战详细过程(DC靶场系列)
Binary tree problem solving (2)
C language practice - number guessing game
win10 磁盘管理 压缩卷 无法启动问题
Flag bits in assembly language: CF, PF, AF, ZF, SF, TF, if, DF, of
Thinkphp内核工单系统源码商业开源版 多用户+多客服+短信+邮件通知
记录一次Unity 2020.3.31f1的bug
win11安装pytorch-gpu遇到的坑
Win10 disk management compressed volume cannot be started
Vmware安装win10报错:operating system not found
Summary of common string processing functions in C language
Wechat applet JWT login issue token
Let正版短信测压开源源码
LM09丨费雪逆变换反转网格策略
洛谷入门3【循环结构】题单题解
unable to execute xxx. SH: operation not permitted