typescript | object-oriented + class + interface + property encapsulation + generics


Object-oriented: All operations in the program need to be done through objects.

  • for example:
    • To operate the browser, use the window object
    • To operate a web page, use the document object
    • The operation console needs to use the console object

class

If you want to be object-oriented and manipulate objects, you must first have objects, so the next question ishow to create objects

To create an object, you must first define a class. The so-called class can be understood as the model of the object. In the program, objects of the specified type can be created according to the class.

For example: Human objects can be created through the Person class, dog objects can be created through the Dog class, and car objects can be created through the Car class. Different classes can be used to create different objects.

constructor constructor, the constructor will be called when the object is created

  • Define class:

      class 类名 {
          
          
      	属性名: 类型;
      	
      	constructor(参数: 类型){
          
          
      		this.属性名 = 参数;
      	}
      	
      	方法名(){
          
          
      		....
      	}
      
      }
    
  • Example:

      class Person{
          
          
          // 定义实例属性
          name: string;
          age: number;
      	// constructor 构造函数,构造函数会在对象创建时调用
          constructor(name: string, age: number){
          
          
          	// this 表示当前的实例
              this.name = name;
              this.age = age;
          }
      
          sayHello(){
          
          
              console.log(`大家好,我是${
            
            this.name}`);
          }
      }
    
  • Use class:

      const p = new Person('孙悟空', 18);
      p.sayHello();
    

Object Oriented Features

  • static property

    • Static properties (methods), also known as class properties. Using static properties does not need to create an instance, it can be used directly through the class

    • Static properties (methods) start with static

    • Example:

       class Tools{
              
              
           static PI = 3.1415926;
           
           static sum(num1: number, num2: number){
              
              
               return num1 + num2
           }
       }
       
       console.log(Tools.PI);
       console.log(Tools.sum(123, 456));
      
  • this

    • In a class, use this to represent the current object

inherit

Inheritance is yet another feature of object-oriented

After using inheritance, the subclass will have all the methods and properties of the parent class.

Properties and methods in other classes can be introduced into the current class through inheritance, and common code in multiple classes can be written in a parent class through inheritance.

  • Example:

        class Animal{
          
          
            name: string;
            age: number;
        
            constructor(name: string, age: number){
          
          
                this.name = name;
                this.age = age;
            }
        }
        
        class Dog extends Animal{
          
          
        
            bark(){
          
          
                console.log(`${
            
            this.name}在汪汪叫!`);
            }
        }
        
        const dog = new Dog('旺财', 4);
        dog.bark();
    

    Extensions to a class can be done without modifying the class through inheritance

rewrite

When inheritance occurs, if the method in the subclass willreplaceDrop the method with the same name in the parent class, which is called method rewriting

  • Example:
      class Animal{
    
    
          name: string;
          age: number;
      
          constructor(name: string, age: number){
    
    
              this.name = name;
              this.age = age;
          }
      
          run(){
    
    
              console.log(`父类中的run方法!`);
          }
      }
      
      class Dog extends Animal{
    
    
      
          bark(){
    
    
              console.log(`${
      
      this.name}在汪汪叫!`);
          }
      
          run(){
    
    
              console.log(`子类中的run方法,会重写父类中的run方法!`);
          }
      }
      
      const dog = new Dog('旺财', 4);
      dog.bark();

super keyword

In the subclass, super can be used to complete the reference to the parent class.
super is used to call the parent class super.xxx
. If a constructor is written in the subclass, the constructor of the parent class must be called in the constructor of the subclass.
insert image description here

abstract class

An abstract class is a class specially designed to be inherited by other classes , it can only be inherited by other classes and cannot be usedcreate instance

    abstract class Animal{
    
    
        abstract run(): void;
        bark(){
    
    
            console.log('动物在叫~');
        }
    }
    
    class Dog extends Animals{
    
    
        run(){
    
    
            console.log('狗在跑~');
        }
    }

A method beginning with abstract is called an abstract method. An abstract method has no method body and can only be defined in an abstract class.

Subclasses must override abstract methods! !

Encapsulation of properties

An object is essentially a container for attributes and methods, and its main function is to store attributes and methods, which is calledencapsulation

By default, the properties of an object can be modified arbitrarily. In order to ensure data security, the permissions of properties can be set in TS

  • Read-only attribute (readonly): If you add one when declaring the attribute readonly, the attribute becomes a read-only attribute and cannot be modified

  • Properties in TS have three modifiers:

    • public (default value): The modified attribute can be accessed (modified) anywhere, which is the default value
    • protected : Protected properties, which can only be accessed and modified in the current class and subclasses of the current class
    • private : Private attributes, which can only be accessed and modified inside the class . Private attributes can be accessed externally by adding methods to the class
  • Example:

    • public

       class Person{
              
              
           public name: string; // 写或什么都不写都是public
           public age: number;
       
           constructor(name: string, age: number){
              
              
               this.name = name; // 可以在类中修改
               this.age = age;
           }
       
           sayHello(){
              
              
               console.log(`大家好,我是${
                
                this.name}`);
           }
       }
       
       class Employee extends Person{
              
              
           constructor(name: string, age: number){
              
              
             // 如果在子类中写了构造函数,在子类的构造函数中必须对父类的构造函数进行调用
               super(name, age);
               this.name = name; //子类中可以修改
           }
       }
       
       const p = new Person('孙悟空', 18);
       p.name = '猪八戒';// 可以通过对象修改
      
    • protected

       class Person{
              
              
           protected name: string;
           protected age: number;
       
           constructor(name: string, age: number){
              
              
               this.name = name; // 可以修改
               this.age = age;
           }
       
           sayHello(){
              
              
               console.log(`大家好,我是${
                
                this.name}`);
           }
       }
       
       class Employee extends Person{
              
              
       
           constructor(name: string, age: number){
              
              
               super(name, age);
               this.name = name; //子类中可以修改
           }
       }
       
       const p = new Person('孙悟空', 18);
       p.name = '猪八戒';// 不能修改
      
    • private

       class Person{
              
              
           private name: string;
           private age: number;
       
           constructor(name: string, age: number){
              
              
               this.name = name; // 可以修改
               this.age = age;
           }
       
           sayHello(){
              
              
               console.log(`大家好,我是${
                
                this.name}`);
           }
       }
       
       class Employee extends Person{
              
              
       
           constructor(name: string, age: number){
              
              
               super(name, age);
               this.name = name; //子类中不能修改
           }
       }
       
       const p = new Person('孙悟空', 18);
       p.name = '猪八戒';// 不能修改
      
  • attribute accessor

    For some properties that do not want to be modified arbitrarily, they can be set to private

    Setting it directly to private will result in no longer being able to modify its properties through the object

    We can define a set of methods to read and set properties in a class. This kind of property that reads or sets properties is called a property accessor

    The method of reading a property is called a getter method, and the method of setting a property is called a setter method

    • Example:

       class Person{
              
              
           private _name: string;
       
           constructor(name: string){
              
              
               this._name = name;
           }
       
           get name(){
              
              
               return this._name;
           }
       
           set name(name: string){
              
              
               this._name = name;
           }
       
       }
       
       const p1 = new Person('孙悟空');
       console.log(p1.name); // 通过getter读取name属性
       p1.name = '猪八戒'; // 通过setter修改name属性
      

Newly added interface (Interface)

The interface is mainly responsible for defining the structure of a class, which is used to define which properties and methods should be included in a class.

An interface can be used to limit the interface of an object, and the object can only match the interface if it contains all the properties and methods defined in the interface .

The interface can be declared repeatedly, and finally all the declared properties and methods will be included.

All properties in the interface cannot have actual values, the interface only defines the structure of the object, regardless of the actual value.

  • Check object type):

    // 定义一个接口
     interface Person{
          
          
         name: string;
         sayHello():void;
     }
    
     function fn(per: Person){
          
          
         per.sayHello();
     }
     
     fn({
          
          
     	name:'孙悟空', 
     	sayHello() {
          
          
     		console.log(`Hello, 我是 ${
            
            this.name}`);
     	}
     });
     
    

At the same time, you can let a class implement the interface, and when implementing the interface, all properties in the interface must be protected in the class.

  • accomplish)

     interface Person{
          
          
         name: string;
         sayHello():void;
     }
      // 定义类时,可以使类去实现一个接口(使类满足接口的要求)
     class Student implements Person{
          
          
         constructor(public name: string) {
          
          
         	this.name = name;
         }
     
         sayHello() {
          
          
             console.log('大家好,我是'+this.name);
         }
     }
    

Generic

When defining a function or class, in some cases the specific type to be used cannot be determined (the types of return values, parameters, and properties cannot be determined), and generics can play a role at this time.

for example:

 function test(arg: any): any{
    
    
 	return arg;
 }

In the above example, the test function has a parameter type that is uncertain , but when it can be determined, the type of the return value is the same as the type of the parameter. Since the type is uncertain , both the parameter and the return value use any, but it is obvious to do so It is inappropriate. Firstly, using any will turn off the type checking of TS. Secondly, this setting cannot reflect that the parameters and return values ​​are of the same type.

We use generics:

 function test<T>(arg: T): T{
    
    
 	return arg;
 }

Here <T>is the generic type, T is the name we give this type (not necessarily called T).
After setting the generic type, you can use T to represent the type in the function. So generics are actually easy to understand, and they represent a certain type.

So how to use the function above?

  • Method 1 (direct use):

       test(10)
    

    When using it, you can pass parameters directly , and the type will be automatically inferred by TS, but sometimes you need to use the following method when the compiler cannot automatically infer

  • Method 2 (specify type):

     	 test<number>(10)
    

    You can also manually specify the generic type after the function

  • Multiple generic types can be specified at the same time, separated by commas:

     function test<T, K>(a: T, b: K): K{
          
          
         return b;
     }
     
     test<number, string>(10, "hello");
    

    When using generics, you can use generics as an ordinary class

  • Generics can also be used in classes:

     class MyClass<T>{
          
          
         prop: T;
     
         constructor(prop: T){
          
          
             this.prop = prop;
         }
     }
    
  • In addition, you can also constrain the scope of generics

     interface MyInter{
          
          
         length: number;
     }
     
     function test<T extends MyInter>(arg: T): number{
          
          
         return arg.length;
     }
    

    Use T extends MyIntermeans that the generic type T must be a subclass of MyInter, and it is not necessary to use interface classes and abstract classes.

Guess you like

Origin blog.csdn.net/muziqwyk/article/details/127008765