This is the 28th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

TypeScript Examples (27)

This article is about TypeScript static members.Copy the code

Static members

We can divide the members of a class into two categories: instance members and static members. You probably know about static members in ES6, but they also exist in TypeScript classes.

Properties and methods decorated with the static keyword in a class are called static properties and static methods, respectively, and are collectively referred to as static members. Static members of a class can use the class name. As a variable name, without the need to create an instance of the class.

Static attributes
/ / 1
class Person {
    static age = 20;
}
console.log(Person.age);   / / 20
Copy the code

The age attribute of example 1 is modified static to become static. Static attributes have the following characteristics: 1. 2. Access attributes by class name. Static properties cannot be inherited by an instance and can only be called by class name.

A static method
/ / 2
class Person {
    static sayHi() {
        return 'hello'}}console.log(Person.sayHi());   // hello
Copy the code

Static methods have the same characteristics as static properties.

Note: There are special attribute names that cannot be used for static member variable names of TypeScript classes. For example, name. If these special attribute names are used, the following syntax error message is displayed: Static property ‘name’ conflicts with built-in property ‘function. name’ of constructor Function ‘Person’

/ / 3
class Person {
    static readonly age = 20;
}
console.log(Person.age);   / / 20
Copy the code

When static members are decorated with other modifiers, the static keyword must precede the other modifiers (such as readonly in Example 3).

Application: Singleton pattern

Those of you who are familiar with design patterns know that a very famous pattern is the singleton pattern. The singleton pattern is one in which only one instance of a class is allowed to be fetched from that class.

/ / 4
class Single {
    private static instance: Single;
    private constructor(public name: string) {}

    static getInstance() {
        if (!this.instance) {
            this.instance = new Single('bear');
        }
        return this.instance; }}const single1 = Single.getInstance();
const single2 = Single.getInstance();
Copy the code

Constructor is made private by the keyword private, so instances cannot be created using the new syntax. Static means to mount a method directly to a class, rather than to an instance of the class. That’s why single.getInstance () is called.

The variables single1 and single2 in example 4 are identical, thus forming a singleton.

Finish this! If this article helps you at all, please give it a thumbs up.