TypeScript object-oriented learning

1. Define the class

Properties of the class:

  • Instance attributes: directly defined attributes, accessed through the instance of the object
  • Static attributes (class attributes): staticat the beginning, no need to create an instance, access through the class
  • Read-only attribute: the readonlybeginning, cannot be modified

Method of the class:

  • Instance method: directly defined method
  • Class method: staticat the beginning, to visit through the class
class Person {
    
    
    // 直接定义的属性
    age = 18;
    // 静态属性(类属性)
    static gender = 'man';
    // 只读属性
    readonly name = 'Jack';

    // 实例方法
    sayHello() {
    
    
        console.log('Hello!');
    }

    // 类方法
    static sayHi() {
    
    
        console.log('Hi!');
    }
}

const Jack = new Person();

console.log(Jack.name);
console.log(Jack.age);
console.log(Person.gender);

Jack.sayHello();
Person.sayHi();

2. Constructor

constructor()Known as the constructor , the constructor is automatically called when the instance object is created .

  • In the instance method, it thisrepresents the current object instance

  • In the constructor, the current object is the newly created object

  • You can thisadd properties to the newly created object

class Dog {
    
    
    name: string;
    age: number;

    constructor(name: string, age: number) {
    
    
        this.name = name;
        this.age = age;
    }

    bark() {
    
    
        console.log(this.name);
    }
}

const dog = new Dog('小黑', 2);
const dog2 = new Dog('小白', 3);

dog.bark(); // 小黑
dog2.bark(); // 小白

3. Inheritance

  • Use keywords to extendsimplement inheritance
  • The child class will have all the methods and properties of the parent class
  • You can add attributes and methods to the subclass that the parent class does not have
  • Override : The same method as the parent class is added to the subclass, then the subclass method will override the parent class method
  • In the method of the class, it superrepresents the parent class of the current class
  • If the subclass write a constructor in the subclass constructor must in the manual for the parent class constructor is invoked ( superindicate parent)
// 父类
class Animal {
    
    
    name: string;
    age: number;

    constructor(name: string, age: number) {
    
    
        this.name = name;
        this.age = age;
    }

    sayHello() {
    
    
        console.log('动物叫~');
    }
}

// 子类:狗
class Dog extends Animal {
    
    
    sayHello() {
    
    
        console.log('wang wang~');
        // super就表示当前类的父类
        super.sayHello();
    }
}

// 子类:猫
class Cat extends Animal {
    
    
    gender: string;

    constructor(name: string, age: number, gender: string) {
    
    
        // 手动调用父类的构造函数,参数为name, age
        super(name, age);
        this.gender = gender;
    }

    run() {
    
    
        console.log(`${
      
      this.name}在跑!`);
    }
    sayHello() {
    
    
        console.log('miao miao~');
    }
}

const dog = new Dog('柯基', 2);
const cat = new Cat('布偶', 4, '雌');

dog.sayHello();
// wang wang~
// 动物叫~

console.log(cat); // Cat { name: '布偶', age: 4, gender: '雌' }
cat.run(); // 布偶在跑!

4. Abstract class, abstract method

  • To abstractclass the beginning of the abstract class
  • An abstract class can not be used to create objects , it is designed to be inherited classes
  • An abstract method can be added to an abstract class , abstractstarting with, there is no method body
  • Abstract methods can only be defined in abstract classes or interfaces , and subclasses must override abstract methods
abstract class Animal {
    
    
    name: string;

    constructor(name: string) {
    
    
        this.name = name;
    }
    abstract sayHello(): void;
}

class Dog extends Animal {
    
    
    age: number;

    constructor(name: string, age: number) {
    
    
        super(name);
        this.age = age;
    }
    sayHello() {
    
    
        console.log(`我是${
      
      this.name}`);
    }
}


const dog = new Dog('旺财', 2);
dog.sayHello(); // 我是旺财

5. Interface

  • Interface is interfaceused to define a class structure , specifying the attributes and methods that should be included

  • Can also be used as a type declaration

  • All attributes in the interface cannot have actual values, only the structure of the object is defined

  • All methods in the interface are abstract methods

  • When defining a class, you can make the class implement an interface

    class 类名 implements 接口名{}

// 定义接口
interface myInterface {
    
    
    name: string;
}

// 补充这个接口
interface myInterface {
    
    
    age: number;
    sayHello(): void;
}

class Person implements myInterface {
    
    
    name: string;
    age: number;
    constructor(name: string, age: number) {
    
    
        this.name = name;
        this.age = age;
    }
    sayHello() {
    
    
        console.log('Hello~');
    }
}

6. Attribute Encapsulation

Attribute modifier

An object is essentially a container for properties and methods, and its main function is to store properties and methods . This is the so-called encapsulation . When defining a class, you can add attribute modifiers before the attribute :

  • public: Public attribute, can be accessed (modified) at any location , default value
  • private: Private attributes, can only be accessed (modified) within a class, but can be used outside the class method access private property
  • protected:Protected attributes, which can only be accessed in the current class and subclasses of the current class (modify)

You can directly define attributes in the constructor , and the following codes at both ends are equivalent :

class Person {
    
    
    name: string;
    age: number;
    constructor(name: string, age: number) {
    
    
        this.name = name;
        this.age = age;
    }
}
class Person {
    
    
    constructor(public name: string, public age: number) {
    
     }
}
// public不能忘记

Attribute accessor

  • For some attributes that do not want to be modified arbitrarily , you can set it toprivate
  • Setting it directly to privatewill result in no longer being able to modify its properties through the object
  • We can define a set of methods for reading and setting properties in the class . The properties that read or set properties are called property accessors.
  • The method of reading the attribute is called the settermethod, and the method of setting the attribute is called the gettermethod
class Person {
    
    
    private age: number;
    constructor(_age: number) {
    
    
        this.age = _age;
    }
    get _age() {
    
    
        return this.age;
    }
    set _age(value) {
    
    
        if (value > 0) {
    
    
            this.age = value;
        }
    }
}

const Tom = new Person(12);
// “age”为私有属性,只能在类“Person”中访问
// 所以访问的是 _age
Tom._age = 18; // 可以更改
console.log(Tom._age); // 18
Tom._age = -18; // 不满足条件,无法更改
console.log(Tom._age); //  18

7. Generic

When defining a function or class , you can use generics if the type is not clear .

function fn<T>(a: T): T {
    
    
    return a;
}

// 可以直接调用具有泛型的函数
let result = fn(10); // 不指定泛型,TS可以自动对类型进行推断
let result2 = fn<string>('hello'); // 指定泛型
// 泛型可以同时指定多个
function fn<T, K>(a: T, b: K): T {
    
    
    console.log(b);
    return a;
}
fn<number, string>(123, 'hello');
// 定义类时可以使用泛型
class MyClass<T>{
    
    
    name: T;
    constructor(name: T) {
    
    
        this.name = name;
    }
}
const Person = new MyClass<string>('Jack');
interface Inter {
    
    
    length: number;
}

// T extends Inter 表示泛型T必须是Inter实现类(子类)
function fn<T extends Inter>(a: T): number {
    
    
    return a.length;
}

Guess you like

Origin blog.csdn.net/Jack_lzx/article/details/115033645