Class I Introduction
Traditional JavaScript programs use functions and prototype-based inheritance to create reusable components.
Starting with ECMAScript 2015, or ECMAScript 6, JavaScript programmers will be able to use the object-oriented approach of classes. But TypeScript allows you to use these features now, without waiting for the next JavaScript version, and compiled JavaScript can run on all browsers and platforms.
Class definitions, access modifiers, accessors, static members
1. public by default
In TypeScript, members of classes default to public, which is different from C#.
2.private
When a member is marked private, his uncle cannot access outside the class.
3.protected
protected modifiers are used to specify members'access to derived classes in inheritance relationships, although this class can also be accessed.
4.readonly
readonly specifies that the property is read-only. It can only be initialized at declaration time or within the constructor.
//readonely modifiers can set properties to read-only, and must be initialized at declaration time or in constructors. class Octopus { readonly name: string; readonly numberOfLegs: number = 8; constructor(theName: string) { this.name = theName; } } let dad = new Octopus('Man with thr 8 strong legs.'); console.info(dad); console.log(dad.name); //dad.name='Zhang Sanfeng'; compiler error, read-only property can not be assigned externally
5. Parametric attributes
Used to combine the definition and replication of attributes, parameter attributes can also specify access modifiers.
//Parameter attributes that combine definition with initialization class Animal { constructor(private name: string) { } move(distanceInMeters: number) { console.log(`${this.name} moved ${distanceInMeters}`); } } let tom = new Animal('Tom Cat'); tom.move(500);
6. Selector geeters/setters
Used for access to attributes, more detailed control
//TypeScript supports getters/setters to control access to members. let passcode = 'secret password'; class Employee { private _fullName: string; get fullName(): string { return this._fullName; } set fullName(newName: string) { if (passcode && passcode == "secret passcode") { this._fullName = newName; } else { console.log('Error:Unauthorized update of employee!'); } } } let employee = new Employee(); employee.fullName = "Blob Smitch"; if (employee.fullName) { alert(employee.fullName); }
7. static attribute
Access can only be accessed using class names, as is the case in current classes, unlike in C #.
//Static properties, using class names to access static members //Specifically, accessing static members in the current class also requires adding a class name, which is different in C #. class Grid { static origin = { x: 0, y: 0 }; static StaticName: string = 'Zhang Sanfeng'; constructor(public scale: number) { } calculateDistanceFormOrigin(point: { x: number, y: number }) { let xDist = (point.x - Grid.origin.x); let yDist = (point.y - Grid.origin.y); return Math.sqrt(xDist * xDist + yDist * yDist) / this.scale; } } let grid1 = new Grid(1.0); let grid2 = new Grid(5.0); console.log(grid1.calculateDistanceFormOrigin({ x: 10, y: 10 })); console.log(grid2.calculateDistanceFormOrigin({ x: 10, y: 10 }));
III. Class Use
1. Inheriting extends
Based on the most basic pattern in object-oriented design, inheritance is allowed to extend existing classes.
class Animal { name: string; constructor(theName: string) { this.name = name; } move(distanceInMeters: number = 0) { console.log(`${this.name} moved ${distanceInMeters}m.`); } } class Snake extends Animal { constructor(name: string) { super(name); } move(distanceInMeters = 5) { console.log('Slithering...'); super.move(distanceInMeters); } } class Horse extends Animal { constructor(name: string) { super(name); } move(distanceInMeters = 45) { console.log('Galloping...'); super.move(distanceInMeters); } } let sam = new Snake('Sammy the Phthon'); let tom = new Horse('Tommy the Palomino'); sam.move(); tom.move(34);
2. abstract class
Abstract classes are used as base classes of other derived classes. They are generally not instantiated.
Unlike interfaces, abstract classes can contain implementation details for members.
Abstract keywords are used to define abstract classes and abstract methods within Abstract classes.
Abstract issuance does not contain concrete implementations and must be implemented in derived classes.
abstract class Animal { abstract makeSound(): void; move(): void { console.log('roaming the earch...'); } }
3. Constructor
The use of a class is declared in TypeScript, and many things are actually declared at the same time. The first is the type of instance of a class, that is, the type of class.
//Use typeof to get variables or references of class types class Greeter { static standardGreeting = 'Hello ,threre'; greeting: string; greet() { if (this.greeting) { return `Hello, ${this.greeting}`; } else { return Greeter.standardGreeting; } } } let greeter1: Greeter; greeter1 = new Greeter(); console.log(greeter1.greet()); //Get variables of class type let greeterMarker: typeof Greeter = Greeter; greeterMarker.standardGreeting = 'Hey ,there!'; let greeter2:Greeter=new greeterMarker(); console.log(greeter1.greet()); console.log(Greeter.standardGreeting);
4. Interface inheritance class
The reason for JavaScript's weak typing is that interfaces are allowed to inherit classes in TypeScript, and members of inherited classes do not include implementations.
class Point{ x:number; y:number; [number:number]:any; static showInfo():void{ console.log(`adasdf`); } } interface Point3d extends Point{ z:number; } let point3:Point3d={ x:1, y:2, z:3 }; console.info(point3); //Point3d.showInfo(); // Definitions in interface inheritance classes do not contain items and compile errors using interface calls
More:
Introduction to TypeScript Interface