This is the 26th day of my participation in the August Text Challenge.More challenges in August


TypeScript – class

(1) Concept

  • A class is a construct of an object-oriented computer programming language. It is a blueprint for creating objects, describing the common properties and methods of the objects created

(2) Definition

The classes here are broadly similar to those in ES6, so the same parts as before are covered briefly here

  • Use the class keyword to define a class, and then use new to create a class-based object

    • usenewWhen the instance is created, the constructor is executed and initialized
    • By addingstaticKeyword to define aStatic properties/methods
    class Person {
        // Static attributes
        name: string = "Ruovan"
        // Member attributes
        age: number
    
        // constructor - performs initialization
        constructor(name: string) {
            this.name = name
        }
    
        // Static method
        static getUserName() {
            return "My name is Ruovan."
        }
    
        // Member methods
        say() {
            return "Hello, My name is " + this.name
        }
    }
    
    // Use new to create an object based on type Gretter
    let person = new Person("Ruovan")
    
    Copy the code

(3) Inheritance

  • Inheritance:

    • Refers to the fact that a class (subclass, subinterface) can inherit from another class (parent class, parent interface) to extend an existing class
    • throughextendsKeyword to implement inheritance
    • Inheritance you can inherit properties and methods from an inherited class, which is called a base class or parent class
    // Base class -- superclass -- superclass
    class Father {
        name = 'Father'
        getFatherName(){
            return this.name; }}// Derived class -- subclass
    class Son extends Father {
        getSonName(){
            return 'Son'}}/ / instance
    const son = new Son()
    
    // getFatherName = getSonName; // getFatherName = getFatherName
    console.log(son.getFatherName()); // Father
    console.log(son.getSonName()) // Son
    
    Copy the code

(4) Rewrite

  • Rewrite:

    • After a subclass inherits a method from a parent class, it can override the parent class’s method in a subclass
    • But at the same time, after rewriting, it can be used againsuperKeyword to re-call the method of the parent class
    class Father {
        name = 'Father'
        getFatherName(){
            return this.name
        }
    }
    class Son extends Father {
        getSonName() {
            return 'Son'
        }
        getFatherName() {
            return 'Son Father'}}/ / instance
    const son = new Son()
    // Subclass getFatherName overwrites parent getFatherName
    console.log(son.getFatherName()) // Son Father
    
    // If Son is written as follows
    class Son extends Father {
        getSonName() {
            return 'Son'
        }
        getFatherName() {
            // super.getName() 
            // use super.getName() to call the methods of the parent class
            return 'new Son' + super.getFatherName() // new Son Father }}Copy the code

(5) Modifier

  • Private types:

    • useprivateTo define aprivateProperties/methods
  • Private types are only allowed inside classes

    class Father {
        private name = 'Father'
        getFatherName(){
            console.log(this.name) // Inside the current class, can be called}}const father = new Father()
    console.log(father.name) // However, this attribute cannot be accessed outside the class, and an error is reported
    
    Copy the code
  • Protection type:

    • useprotectedTo define a protected property/method
    • Protected types are only allowed inside classes and in inherited subclasses
    class Father {
        protected name = 'Father'
        getFatherName(){
            console.log(this.name) // Inside the current class, can be called}}class Son extends Father {
        getSonName() {
            console.log(this.name) // Name inherited from the parent class is allowed to be called}}Copy the code
  • Common type:

    • usepublicTo define a common property/method
    • All default properties/methods are preceded bypublic, so it may not be written, and the common type is allowed inClass outsideuse
    class Father {    
        / / public by default
        name = 'Ruovan'
        // public name = 'Ruovan'
        getFatherName(){        
            console.log(this.name)    
        }
    }
    const father = new Father()
    console.log(father.name)
    
    Copy the code
  • Read-only type: Use readonly to define a read-only property

    • Read-only attributes must be initialized at declaration time or in a constructor
    • The read-only property cannot be changed after it is initialized
    class Father {    
        readonly name: string = 'Ruovan'    
        constructor(name: string) {        
            this.name = name    
        }
    }
    let father = new Father('Ruovan')
    father.name = 'composition' // error
    
    Copy the code

(6) Constructor

  • When an instance is created using new, the constructor() function is executed immediately

    class Person {    
        let name: string    
        constructor(name: string) {        
            this.name = name    
        }
    }
    const person = new Person('Ruovan')
    
    Copy the code
  • Parameter properties:

    • Parameter properties make it easy to define and initialize a member in one place
    • Only used in constructorsreadonly name: stringParameters to create and initializenameMembers of the
      • That is, declarations and assignments are combined to simplify the code
    class Person {    
        constructor(readonly name: string) {    
            this.name = name
        }
    }
    const person = new Person('Ruovan')
    console.log(person.name)
    
    Copy the code
  • Inheritance:

    • If the parent class has a constructor and the child class has a constructor, the child class must call the parent constructor and must pass the parameters required by the parent constructor
    class Father{
        constructor(public name:string){}}class Son extends Father{
        constructor(public age:number){
            super('Ruovan')}}const son = new Son(24)
    console.log(son.age) / / 24
    console.log(son.name) // Ruovan
    
    Copy the code

(7) Access

  • Access 7: this property can be read and changed

    • throughgetters/settersTo intercept access to an object member
      • Variables are processed in this method and then exposed
    • At the same time, the outside world can call directlyget/setTo read or change the property
    class Person {
        firstName: string = 'A'
        lastName: string = 'B'
        get fullName () {
            return this.firstName + The '-' + this.lastName
        }
        set fullName (value) {
            const names = value.split(The '-')
            this.firstName = names[0]
            this.lastName = names[1]}}const person = new Person()
    console.log(person.fullName) // A-B
    
    person.firstName = 'C'
    person.lastName =  'D'
    console.log(person.fullName) // C-D
    
    person.fullName = 'E-F'
    console.log(person.firstName, person.lastName) // E F
    
    Copy the code

(8) Singleton mode

  • The singleton pattern means that only one instance is ever generated

    • throughinstanceKeyword to judge
    class Demo{
        private static instance:Demo 
        // It is not allowed to be called to circumvent instance creation
        private constructor(public name:string){}static getInstance(){
            if(!this.instance){ // If no instance is created let instance store
                this.instance = new Demo('demo')}return this.instance
        }
    
    }
    const demo = Demo.getInstance()
    
    Copy the code

(9) Abstract classes

  • Abstract class: that is, the parts with the same attributes are encapsulated, and the concrete content is defined by the subclass

    • throughabstractThe keyword defines an abstract class
    • Note that:
      • Abstract classes can only be inherited and cannot be used to create instances
      • When a subclass inherits an abstract class from a parent class, it must implement the parent class’s abstract methods in the subclass
    // abstract defines an abstract class
    abstract class Person{
        getClass(){
            return 'Person'
        }
        // Abstract method, only one method, no concrete implementation
        abstract getSex(): string
    }
    class Woman extends Person {
        // Implement a concrete abstract class method in a subclass
        getSex(){
            return 'female'}}class Man extends Person {
        getSex(){
            return 'male'}}Copy the code

I front-end side dish chicken, if there is wrong, please forgive