This is the 15th day of my participation in the August More Text Challenge. For details, see:August is more challenging

  • inheritance

    1. In TypeScript, we can use the usual object-oriented patterns. One of the most basic patterns in class-based programming is to allow the use of inheritance to extend existing classes
Class Pig extends Animal{name:string {return '${STR} ~'}} class Pig extends Animal{name:string Constructor (name:string){super() this.name = name}} let student = new Pig(' constructor '); constructor(){super() this.name = name}} let student = new Pig(' constructor '); Console.log (student.eat(' pork shop '))Copy the code
  1. This example shows inheritance at its most basic: a class inherits properties and methods from a base class. herePigIs a derived class, which is derived fromAnimalBase class, throughextendsThe keyword. Derived classes are usually called subclasses, and base classes are usually called superclasses.

Since Pig inherits the functions of Animal, we can create an instance of Pig that can be bark().

  • Ts has a static member modifier; Js has the same modifier, which is eventually resolved to a property of the class itself (or, in ES5, a property of the function). Static properties can be referenced anywhere directly by the class name.

  • Ts has a readonly member modifier; Js does not have this modifier, but it can be implemented through the property accessor GET.

Class Info{readonly name:string constructor(name:string){this.name = name}} let student = new Info(' constructor '); class Info{readonly name:string constructor(name:string){this.name = name}} let student = new Info(' constructor '); Student. name = 'xiao Mei'Copy the code

In this example, we define the property name as a read-only property, and we will report an error when assigning it. The read-only property must be initialized at declaration or in the constructor.

  • Creates static members of a class whose properties exist on the class itself rather than on instances of the class
  1. Static properties are defined in ES6: these properties exist on the class itself, not on an instance of the class, and can only be passed through the class. Property name, but cannot be invoked on an instance.
class Animal{ static eat(str:string):void{ console.log(this); }} let pig = new Animal() pig.eat(" ice cream "); // Animal. Eat (' ice cream ')Copy the code

Pig. eat is an error, because by default the constructor this refers to the instance generated by the constructor, and instances do not inherit from static methods.