Define a class using the class keyword
* const per = new Person(); * const per = new Person(); * per.name /* // Define instance attribute name:string = 'Tom '; Person.age static age:number = 12; person. age static age:number = 12; /* * If the method is static, then the method is class. */ sayHello(){console.log(' hello ')}} const per = new Person() // Access the instance property console.log(per.name) // Tom // Log (person.age) // 12 // Instance properties to change per.name = 'suddy' console.log(per.name) // suddyCopy the code
Class inheritance
Function (){// Define a class Dog{name:string; age:number; constructor(name:string,age:number){ this.name = name ; this.age = age; SayHello (){console.log(' hello ')}} // Define a class Cat{name:string; age:number; constructor(name:string,age:number){ this.name = name; thia.age = age; } asyHello(){console.log(' hello ')}}})();Copy the code
Two classes have common attributes and methods, and can be merged into one as follows:
class Animal{ name:string; age:number; constructor(name:string,age:number){ this.name = name; thia.age = age; } asyHello(){console.log(' language ')}} Subclasses will all the methods and properties of a parent class * - through inheritance can be multiple classes of the communist party of China to write some code in a parent class * - so you just need to write a let all subclasses also have properties and methods of the parent * - if you want to add some in subclasses in the parent class no properties or methods can be added to * - directly If you add the same method as the parent, the subclass method overrides the parent method * - this subclass overrides the parent method form, Class Dog extends Animal{run(){console.log('${this.name} + running ')} sayHello(){console.log('hello')}} console.log(dog.run())Copy the code
An abstract class
/* * - Classes that begin with abstract are abstract classes * - Abstract classes are not much different from other classes, You can add abstract methods */ abstract class Animal{// Define an abstract method // Abstract methods start with abstract, // Abstract methods can only be defined in abstract classes. Subclasses must override abstract methods. } class Dog extends Animal{ } const an = new Animal()Copy the code