当前位置:网站首页>TS class
TS class
2022-07-25 23:17:00 【Intern Sen】
TS class
TypeScript It's object-oriented JavaScript. Class describes the common types and methods of the created objects .
TypeScript Support all object-oriented features , such as class 、 Interfaces, etc. .
1 Define the way
The keyword defining the class is class, Followed by the class name .
class class_name {
// Class scope
}
Class can contain the following modules ( Data members of class ):
Field : A field is a variable declared in a class , The field represents the relevant data of the object .
Constructors : Class instantiation calls , You can allocate memory for objects of classes .
Method : Method is the operation to be performed by the object .
2 Create a data member of the class
Declared class Car, The containing field is engine, Constructor initializes fields after class instantiation engine.
this Keyword indicates the currently instantiated object .
At the same time, a method is also defined in the class disp().
Be careful : The parameter name of the constructor is the same as the field name ,this.engine Fields representing classes .
class Car {
engine:string; // Field
constructor(engine:string) {
// Constructors
this.engine = engine
}
disp():void {
// Method
console.log(" The engine is : "+this.engine)
}
}
3 Create instantiated objects
Use new Keyword to instantiate the object of the class
var object_name = new class_name([arguments])
var obj = new Car("Engine 1")// Class instantiation will call the constructor , for example
The field properties and methods in the class can use . Number access :
obj.field_name() // Access properties
obj.function_name() // Access method
A complete example :
class Car {
engine:string; // Field
constructor(engine:string) {
// Constructors
this.engine = engine
}
disp():void {
// Method
console.log(" The engine model is displayed in the function : "+this.engine)
}
}
var obj = new Car("XXSY1") // Create an object
console.log(" Read engine model : "+obj.engine) // Access field
obj.disp() // Access method
// Output results
// Read engine model : XXSY1
// The engine model is displayed in the function : XXSY1
4 Class inheritance
Use keywords extends Inheritance class , That is, you can inherit an existing class when creating a class .
class child_class_name extends parent_class_name
This existing class is called the parent class , The class that inherits it is called a subclass .
Subclasses cannot inherit private members of the parent class ( Methods and properties ) And constructor , Everything else can be inherited .
A complete example : Instance created Shape class ,Circle Class inherited Shape class ,Circle Class can be used directly Area attribute
class Shape {
Area:number
constructor(a:number) {
this.Area = a
}
}
class Circle extends Shape {
disp():void {
console.log(" Area of circle : "+this.Area)
}
}
var obj = new Circle(223);
obj.disp()
TS You can only inherit one class at a time , Inheriting multiple classes is not supported .
Support multiple inheritance .(A Inherit B,B Inherit C).
Multiple inheritance instances :
class Root {
str:string;
}
class Child extends Root {
}
class Leaf extends Child {
} // multiple inheritance , Inherited Child and Root class
var obj = new Leaf();
obj.str ="hello"
console.log(obj.str)
5 Method overrides of inherited classes
After class inheritance , Subclasses can redefine the methods of the parent class , This process is called method rewriting .
among super A keyword is a direct reference to a parent class , This keyword can refer to the properties and methods of the parent class .
class PrinterClass {
doPrint():void {
console.log(" Of the parent class doPrint() Method .")
}
}
class StringPrinter extends PrinterClass {
doPrint():void {
super.doPrint() // Calls a function of the superclass
console.log(" A subclass doPrint() Method .")
}
}
6 static keyword
static Keyword is used to define the data members of a class ( Properties and methods ) For static . Static members Can be called directly through the class name .
class StaticMem {
static num:number;
static disp():void {
console.log("num The value is "+ StaticMem.num)
}
}
StaticMem.num = 12 // Initialize static variables
StaticMem.disp() // Call static methods
7 instanceof Operator
instanceof Operator is used to determine whether the object is of the specified type , If yes, return true, Otherwise, return false.
class Person{
}
var obj = new Person()
var isPerson = obj instanceof Person;
console.log("obj The object is Person Class instantiation ? " + isPerson);
//obj The object is Person Class instantiation ? true
8 Access control modifiers
TS Can be used in Access control character To protect the class 、 Variable 、 Access to methods and constructors .
Support 3 Different access rights .
public: share , Can be visited anywhere ( Default )
protected: The protected , Can be accessed by itself and its subclasses
private: private , Can only be accessed by the class in which it is defined
A complete example :
Two variables are defined str1 and str2,str1 by public,str2 by private,
After instantiation, you can access str1, If you want to access str2 It will compile errors .
class Encapsulate {
str1:string = "hello"
private str2:string = "world"
}
var obj = new Encapsulate()
console.log(obj.str1) // Accessible
console.log(obj.str2) // Compile error , str2 Is private
9 Classes and interfaces
Class can implement interfaces , Use keywords implements, And will interest Fields are used as properties of the class .
interface ILoan {
interest:number
}
class AgriLoan implements ILoan {
interest:number
rebate:number
constructor(interest:number,rebate:number) {
this.interest = interest
this.rebate = rebate
}
}
var obj = new AgriLoan(10,1)
console.log(" Profit is : "+obj.interest+", Draw into : "+obj.rebate )
// Profit is : 10, Draw into : 1
边栏推荐
- About priority queues
- Rental experience post
- POI特效 市场调研
- Zero crossing position search of discrete data (array)
- QT string operation
- The small icon of notification setting shows a small square
- [opencv] edge detection [API and source code implementation]
- 模拟实现string类常用接口
- [QNX Hypervisor 2.2用户手册]9.8 load
- Sichuan cuisine menu (I)
猜你喜欢

电商RPA,大促轻松上阵的法宝

Enterprise level inventory management system of code audit

VisualBox启动虚拟机报错:The VM session was closed before any attempt to power it on.

Very simple vsplayaudio online music player plug-in

MathType安装和解决不能Crtl+V的问题

Zero crossing position search of discrete data (array)

Discuz atmosphere game style template / imitation lol hero League game DZ game template GBK

How does Navicat modify the language (Chinese or English)?

Take root downward, grow upward, and explore the "root" power of Huawei cloud AI

单模型常识推理首超人类!HFL登顶OpenBookQA挑战赛
随机推荐
serialization and deserialization
@Autowired annotation required attribute
Firewall command simple operation
r语言绘图参数(R语言plot画图)
[QNX Hypervisor 2.2用户手册]9.7 generate
Enabling partners, how can Amazon cloud technology "get on the horse and get a ride"?
QT string operation
Summary of built-in instructions and custom instructions
The small icon of notification setting shows a small square
AI chief architect 12 AICA industrial landing analysis under the industrial production process optimization scenario
Notification(状态栏通知)详解
Design of Butterworth filter and drawing of amplitude frequency characteristic curve
Thinkphp6 temporarily close the layout
策略模式_
Discuz magazine / news report template (jeavi_line) utf8 GBK / DZ template download
PHP JSON variable array problem
ZCMU--5015: 完成任务
About priority queues
Classes and objects (2) (6 default member functions)
Call Gaode map -- address is converted into longitude and latitude