The use and inheritance of ts class class, the new class class of es6

Foreword:

        The use and inheritance of the class class of ts, the new class class of es6.

1. The new class class in es6

        In ES6, in order to better design js into the grammatical features of an object-oriented language, the class class is proposed. The essence of a class is a function. The class cannot be declared repeatedly, and the class definition will not be promoted, making js more like object-oriented programming. grammar.

        It is recommended to capitalize the class name, and it must be capitalized under strict requirements.

        Declare class: class class name {}   

        Anonymous class: var fn = class {}

        An instance of a class is an object, and objects have three major characteristics: encapsulation, inheritance, and polymorphism .

1. Packaging

class Animal{
    constructor(name){ //接收参数
        this.name = name
    }
    run(){
        console.log( this.name+'可以跑起来!')
    }
}
 
console.log(111);
const dog = new Animal('小黑')
dog.run()

2. Inheritance

1. Use the extends keyword to implement inheritance

2. Subclasses can inherit all the methods and properties of the parent class

3. A subclass can only inherit from one parent class (single inheritance), and a parent class can have multiple subclasses

4. There must be super() in the construction method of the subclass to specify the construction method of the parent class, and it is located in the first line of the construction method of the subclass

5. If the subclass has the same methods and properties as the parent class, the subclass will be used first (override)

class Dog extends Animal{
    bark(){
        return `${this.name} 是一只狗`
    }
}
console.log(222);
const mazi = new Dog('王麻子')
mazi.run()
console.log(mazi.bark)

3. Polymorphism

class JinMao extends Dog{
    static categories = ['manmal']  //static-修饰符,静态属性
 
    constructor(name){                    
        super(name)  //子类构造函数中必须用super()
        consoe.log(this.name)
    }
 
    run(){
        return 'memow'+super.run()  //调用父类的run函数
    }
} 
 
console.log(333);
const maomao = new JinMao('maomao')
maomao.run()

//static 定义的变量和方法,可以直接用  方法名+点+变量/方法名()   调用
console.log(  JinMao.categories  );

Printing effect:

2. The new class method of ts

The class in ts adds three more modifiers, which are used to set permissions for the attributes and methods in the class, which is easier to manage.

  • public: The modified properties and methods are shared by default;
  • private: The modified properties and methods are private and can only be used in the class, and cannot be used by new instances or inherited subclasses of this class;
  • protected: The modified properties and methods are protected and can be used by inherited subclasses.

1、public

class Animal {
  public name;
  public constructor(name) {
    this.name = name;
  }
}

let a = new Animal('Jack');
console.log(a.name); // Jack
a.name = 'Tom';
console.log(a.name); // Tom

2、private

class Animal{
    private run(){
        return `${this.name} is running`
    }
}
 
const snake = new Animal()
console.log(snake.run())            //报错,run已变成私有方法,不能被使用

3. Protected inherited subclasses can use

class Animal {
  protected name;
}

class Cat extends Animal {
  constructor(name) {
    super(name);
    console.log(this.name);
  }
}

4. readonly read-only attribute,

Note that if  readonly it exists with other access modifiers, it needs to be written after it.

class Animal {
  readonly name;
}

let a = new Animal();
console.log(a.name); // Jack
a.name = 'Tom';   //无法修改

Three, the interface interface in ts

We use interfaces (Interfaces) to define the type of object, interface (Interfaces) is a very important concept, it is an abstraction of behavior, and how to act specifically needs to be implemented by classes (classes)

The interface declaration only exists in the compilation phase, and the JS code generated after compilation does not contain any interface code

Implementation of common interface:

interface Person {
  name: String  //必传
  age?: Number  // ?:可传可不传
}

//调用1:格式必须和接口的格式一致,多属性,少属性都不行
let tom: Person = {
    name: 'Tom'
};

//调用2:
let tom: Person = {
    name: 'Tom',
    age: 25
};

Any property of the interface: [propName: string]

* Once any property is defined, the type of both definite and optional properties must be a subset of its type

interface Person {
    name: string  //确定属性,之前就是必传
    age?: number  //可传属性,之前就是不必传,使用任意属性以后,必传
    [propName: string]: string | number  //任意属性,加上以后,对象里面可以有任意多对象
    //[propName: string]: string  如果这样写会报错,因为 age的值是number
}

//调用1:格式必须和接口的格式一致,多属性,少属性都不行
let tom: Person = {
    name: 'Tom',
    age: 25,
    gender: 'male'
}
//调用2
let tom: Person = {
    name: 'Tom',
    age: 25,
    gender: 'male',
    aaa: '123'
}

read-only property of the interface

Note that the read-only constraint exists when the object is first assigned

interface Person {
    readonly id: number
    name: string
    age?: number
    [propName: string]: any
}

let tom: Person = { 
    id: 89757, // 初始化 对象赋值,是成功的
    name: 'Tom',
    gender: 'male'
};

tom.id = 9527; //  再次赋值,会报错,因为id是只读属性

4. The difference between type and interface in ts

1. Difference

same:

        can be used to define  the structure of objects  or  functions  , and strictly speaking, type is a reference, interfacebut a definition

different:

1. type (alias) type alias, which can define basic type, joint type or cross type. interface interface, only objects can be defined,

2. Interfaces can extend and implements, thereby extending multiple interfaces or classes. type has no extension function and can only be cross-merged

3. Defining two interfaces with the same name will merge the declarations, and defining two types with the same name will cause an exception.

4. type is actually an assignment operation after declaring the type alias , which needs to associate the alias with the type . That is to say, the type alias does not create a new type, it just names the existing type and directly refers to it. interfaceis to define an interface type

// 1、定义声明不同
type Person = string
type animal = Dog | Cat
//type定义元组
interface Dog {
  name: string;
}
interface Cat {
  age: number;
}
type animal = [Dog, Cat];

//接口定义对象
interface Person {
    name: string
}



// 2、定义两个相同名称的接口会合并声明,定义两个同名的 type 会出现异常
interface Person {
  name: string;
}
interface Person {
  age: number;
}
// 合并为:interface Person { name: string age: number}

type User = {
  name: string;
};
type User = {
  age: number;
};
// 声明重复报错:标识符“User”重复。

2. Inheritance of interface

Interfaces can extend and implements to achieve inheritance

//extends 可以实现class继承,也可以实现接口继承
interface Person {
  name: string;
}
interface User extends Person {
  age: number;
}



interface Animal {
    food: string
    eat(food: string): void
}
// Cat类实现Animal接口的时候需要能够兼容Animal接口才行,否则会报错。
class Cat implements Animal {
    food: string = 'fish';
    eat(food: string): void {}
}

3. type uses cross type & to merge the types of different members to achieve an effect similar to inheritance

type Person = { name: string }; //1、type定义对象
type User = Person & { age: number }; //2、type合并两个对象

interface Person {
  name: string;
}
type User = { age: number } & Person; //3、type合并对象和接口

Guess you like

Origin blog.csdn.net/qq_41619796/article/details/129853838