definition
Class is the basis of information encapsulation in Object-Oriented Programming (OOP)
❝
Class is a user-defined reference data type, also known as class type
❞
Traditional object-oriented languages are basically based on classes. The prototype based approach of JavaScript makes developers have a lot more understanding costs
After ES6, JavaScript has the class keyword. Although it is still a constructor in essence, it is much easier to use
However, JavaScript class still has some features that have not been added, such as modifiers and abstract classes
TypeScript class supports all object-oriented features, such as classes, interfaces, etc
Mode of use
The keyword defining the class is class, followed by the class name. The class can contain the following modules (data members of the class):
Field: a field is a variable declared in a class. Fields represent data about the object.
Constructor: called when the class is instantiated, it can allocate memory for the object of the class.
Method: the operation to be performed by the method object
Examples are as follows:
class Car { // field engine:string; // Constructor constructor(engine:string) { this.engine = engine } // method disp():void { console.log("Engine is : "+this.engine) } }
inherit
Class inheritance used the extends keyword
class Animal { move(distanceInMeters: number = 0) { console.log(`Animal moved ${distanceInMeters}m.`); } } class Dog extends Animal { bark() { console.log('Woof! Woof!'); } } const dog = new Dog(); dog.bark(); dog.move(10); dog.bark();
Dog is a derived class derived from the Animal base class. Derived classes are often called subclasses and base classes are often called superclasses
The dog class inherits the Animal class, so the instance dog can also use the move method of the Animal class
Similarly, after class inheritance, the subclass can redefine the methods of the parent class. This process is called method rewriting. The super keyword is a direct reference to the parent class. This keyword can reference the properties and methods of the parent class, as follows:
class PrinterClass { doPrint():void { console.log("Parent class doPrint() method.") } } class StringPrinter extends PrinterClass { doPrint():void { super.doPrint() // Call the function of the parent class console.log("Subclass doPrint()method.") } }
Modifier
It can be seen that the above form is very similar to ES6. typescript adds three modifiers on this basis:
public: members defined in class programs can be accessed freely
private: it can only be accessed inside this class
Protected: in addition to being accessible inside the class, it can also be accessed in subclasses
Private modifier
It can only be accessed inside the class, and the instance object cannot be accessed
And subclasses that inherit this class cannot be accessed, as shown in the following figure:
Protected modifier
Similar to private modifiers, instance objects cannot access protected properties, as follows:
One difference is that protected members are still accessible in subclasses
In addition to the above modifiers, there are read-only "modifiers"
Read only modifier
Declared through the readonly keyword, the read-only attribute must be initialized in the declaration or constructor, as follows:
In addition to instance properties, there are also static properties
Static properties
These attributes exist on the class itself rather than on the instance of the class. They are defined through static. Accessing these attributes requires the form of type. Static attributes, as shown below:
class Square { static width = '100px' } console.log(Square.width) // 100px
One feature of the above classes is that they can be instantiated. There is also an abstract class in typescript
abstract class
Abstract classes are used as the base classes of other derived classes. They are generally not instantiated directly. Unlike interfaces, abstract classes can contain the implementation details of members
Abstract keyword is used to define abstract classes and abstract methods within abstract classes, as shown below:
abstract class Animal { abstract makeSound(): void; move(): void { console.log('roaming the earch...'); } }``` This class cannot be instantiated. We usually need to create subclasses to inherit, as follows: ```javascript class Cat extends Animal { makeSound() { console.log('miao miao') } } const cat = new Cat() cat.makeSound() // miao miao cat.move() // roaming the earch...
Application scenario
In addition to completing daily business codes with the help of the characteristics of classes, classes can also be used as interfaces, especially in React engineering, as follows:
export default class Carousel extends React.Component<Props, State> {}
Because the component needs to pass in the type props of props and set the default props, that is, defaultProps, it is more suitable to use class as the interface
Specify a class that contains the type and initial value required by the component props:
// Types of props export default class Props { public children: Array<React.ReactElement<any>> | React.ReactElement<any> | never[] = [] public speed: number = 500 public height: number = 160 public animation: string = 'easeInOutQuad' public isAuto: boolean = true public autoPlayInterval: number = 4500 public afterChange: () => {} public beforeChange: () => {} public selesctedColor: string public showDots: boolean = true }
When we need to pass in props type, we directly pass in props as an interface. At this time, props is used as an interface. When we need to set the default props initial value, we only need to:
public static defaultProps = new Props()
The example of Props is the initial value of defaultProps, which is the practical application of class as an interface. We use one class to play the two roles of interface and setting the initial value, which is convenient for unified management and reduces the amount of code