ECMAScript past

Before ES6, there was no such thing as a class, and the same effect was achieved through constructors, with inheritance implemented through a chain of prototypes.

Typescript has other features besides implementing the ES6 class. Let’s see.

Concept cross talk literacy

  • Classes, which define the abstract properties of things (properties and methods);
  • Abstract class, a base class that can be inherited by other classes (instantiation is not allowed). Abstract methods must be implemented in subclasses.
  • Interface: A public property or method of a different class that can be abstracted into an interface that can be implemented by a class. Class inheritance can only be one, but can be implemented multiple times;
  • Setters and getters: assigning and reading properties;
  • Modifiers: Keywords that limit the properties of members or types (public, Protect, private) supported by Typescript.
  • Object, an instance of a class, passesnewGeneration implementation;
  • Object-oriented (OOP) features: encapsulation, inheritance, and polymorphism;
  • Encapsulation: Hides the processing details of data attributes and exposes only interfaces. External calls can access the object without knowing the details, which also ensures that external calls cannot change internal data attributes;
  • Inheritance: A subclass inherits its parent class. A subclass has all the features of its parent class and can also have its own specific features.
  • Polymorphism: the generation by inheritance of different classes that respond differently to the same approach;

Use of ES6 classes

ES6 is familiar to us all. Generating an instance with new automatically calls the constructor, which is defined by constructor.

Instances, constructors, properties, and methods

// es6.js
class Animal {
    constructor(name) {
        this.name = name;
    }
    showName() {
        return I was `The ${this.name}`}}let animal = new Animal('animals');
console.log(animal.showName()); // I am an animal
Copy the code

Inheritance and polymorphism

Derived classes use extends for inheritance and super to perform the constructor of the base class.

  • The base class is the superclass or parent class;
  • A derived class is a subclass;
// es6.js
class Cat extends Animal {
    // constructor does not have its own attributes
    constructor(name) {
        super(name);
    }

    showName() {
        return 'I'm a dogThe ${this.name}`}}let cat = new Cat('the cat');
console.log(cat.showName()); // I am a cat
Copy the code

accessor

// es62.js
class Animal {
    constructor(name) {
        this.name = name;
    }
    get newName() {
        return ` access:The ${this.name}`;
    }
    set newName(value) {
        this.name = ` new${value}`}}let animal = new Animal('animals');
animal.newName = 'Big Animal';
console.log(animal.newName);
Copy the code

A static method

Static is used to define methods for your own use, so no instantiation is required and instances cannot be called.

// es63.js
class Animal {
    static isAnimal(animal) {
        return animal instanceofAnimal; }}let animal = new Animal('animals');
console.log(Animal.isAnimal(animal)); // true
console.log(animal.isAnimal(animal)); // TypeError: animal.isAnimal is not a function
Copy the code

ES7 class usage

Instance attributes

In ES6, instance attributes are defined in the constructor construction; in ES7, they can be written directly inside the class.

// es64.js
class Animal {
    name = 'animals';

    constructor() {
        // ...}}let animal = new Animal();
console.log(animal.name); / / animals
Copy the code

Static attributes

Since instance attributes can be defined directly in a class, static attributes can be defined in the same way

// es65.js
class Animal {
    static name = 'animals';

    constructor() {
        // ...}}let animal = new Animal();
console.log(Animal.name); / / animals
console.log(animal.name); // undefined
Copy the code

Typescript class usage

The obvious and not new modifiers public, private, protected, and Readonly have been added.

  • publicThe modified properties and methods are public and can be used arbitrarily.
  • privateThe modified properties and methods are private and used only by the class itself;
  • protectedThe modified properties and methods are protected and used only by the class itself and its subclasses;
  • readonlyThe modified property is read-only and must be initialized at declaration time or in a constructor;
// class.ts
class Star {
    public name: string = 'pr';
    protected age: number = 18;
    private weight: number = 90;
    readonly gender: string = 'woman';

    public constructor(name: string, age: number, weight: number, gender: string) {
        this.name = name;
        this.age = age;
        this.weight = weight;
        this.gender = gender; }}class ChinaStar extends Star {
    constructor(name: string, age: number, weight: number, gender: string) {
        super(name, age, weight, gender);
    }

    showName(){
        return I was `${this.name}`
    }

    showAge(){
        return 'My real age${this.age}`
    }

    showWeight(){
        return 'My weight${this.weight}`
    }

    showGender(){
        return 'My sex${this.gender}`}}let pr = new ChinaStar('pr'.30.120.'male');
pr.name = 'See you later';
pr.age = 18;
pr.weight = 100;
pr.gender = 'woman';

console.log(pr.name);
console.log(pr.age);
console.log(pr.weight);
console.log(pr.gender);

console.log(pr.showName());
console.log(pr.showAge());
console.log(pr.showWeight());
console.log(pr.showGender());

// 0.0.9/class.ts: 29:28-error TS2341: Property 'weight' is private and only accessible within class 'Star'.
    // 29 return 'my weight ${this.weight}'

// 0.0.9/class.ts:39:4 - error TS2445: Property 'age' is protected and only accessible within class 'Star' and its subclasses.
    // 39 pr.age = 18;
      
// 0.0.9/class.ts: 40:4-error TS2341: Property 'weight' is private and only accessible within class 'Star'.
    // 40 pr.weight = 100;
      
// 0.0.9/class.ts: 41:4-error TS2540: Cannot assign to 'gender' because it is a read-only property.
    // 41 pr. Gender = 'female ';
      
// 0.0.9/class.ts:44:16 - error TS2445: Property 'age' is protected and only accessible within class 'Star' and its subclasses.
    // 44 console.log(pr.age);
       
// 0.0.9/class.ts:45:16 - error TS2341: Property 'weight' is private and only accessible within class 'Star'.
    // 45 console.log(pr.weight);
Copy the code

You can see that in the example

  • Only attributesnameCan be used in an instance;
  • Only attributesnameageCan be used in subclasses;
  • Cannot be assigned to “gender” because it is read-only;

Note: It is a Typescript requirement that the base class constructor call super() before using this.

An abstract class

Is not instantiated and is only used by base classes. The Abstract keyword can be used to define an Abstract class and its internal defined Abstract methods. Unlike interfaces, abstract classes can contain implementation details of members.

// abstract.ts
abstract class Animal2 {
    abstract say(): void;
    move(): void{
        console.log('mobile'); }}Copy the code

An abstract method in an abstract class has no implementation (much like an interface, which defines a method signature without a method body), but must be implemented in a derived class.

// abstract2.ts
/ / abstract classes
abstract class AbstractPerson {
    constructor(public name: string.public age: number.public weight: number) { }

    showName(): string {
        return 'My name is${this.name}`;
    }

    abstract showAge(): void;
}

/ / the base class
class Person extends AbstractPerson {
    constructor(name: string, age: number, weight: number) {
        super(name, age, weight);
    }
    showAge(): void {
        console.log('My age${this.age}`)
    }
    showWeight(): void {
        console.log('My weight${this.weight}`)}}let person1: AbstractPerson;
let person2: AbstractPerson;

person1 = new AbstractPerson('pr'.30.110);
person2 = new Person('pr'.30.110);

console.log(person2.showName());
person2.showAge();
person2.showWeight();


Abstract2.ts: 29:11-error TS2511: Cannot create an instance of an abstract class.
    // 29 person1 = new AbstractPerson('pr', 30, 110);
       
// abstract2.ts: 34:9-error TS2339: Property 'showWeight' does not exist on type 'AbstractPerson'.
    // 34 person2.showWeight();
Copy the code
  • Cannot generate instance for abstract class;
  • methodsshowWeightIn an abstract classAbstractPersonUpper middle does not exist;

This code Github

You can…

Previous: Typescript enumerations

Next: Typescript classes and interfaces

Contents: A primer to Typescript’s short book