1. Class inheritance and primitive type designation
In ts, super must be called, otherwise it will prompt
Constructors for derived classes must contain a 'super' call
Super takes three forms in subclasses: 1. Represents the constructor of the parent class in the constructor of the subclass. 2. A prototype object that is equivalent to the parent class in the ordinary function of a subclass. Equivalent to the parent class itself in a static function of a subclass.
class Animal { name: string; constructor(theName: string) { this.name = theName; } move(distanceInMeters: number = 0) { console.log(`${this.name} moved ${distanceInMeters}m.`); } } class Horse extends Animal { constructor(name: string) { super(name); } // 1. Equivalent to super.call(this, props) move(distanceInMeters = 45) {console.log("Galloping... ); / / 2. Equivalent to a super. Prototype. Move the call (this, distanceInMeters) super. Move (distanceInMeters); } } let tom: Animal = new Horse("Tommy the Palomino"); tom.move(34);Copy the code
2. Modifiers (public/private/protected)
1. The public – the public
In TS, all members of a class default to public. It can be accessed at will
The above class is essentially:
class Animal { public name: string; public constructor(theName: string) { this.name = theName; } public move(distanceInMeters: number = 0) { console.log(`${this.name} moved ${distanceInMeters}m.`); }}Copy the code
2. Private – private
It can only be accessed inside the class that declares it
class Animal { private name: string; constructor(theName: string) { this.name = theName; }}new Animal("Cat").name; // Error: 'name' is private.Copy the code
Members of private can be inherited
class Animal { private name: string; constructor(theName: string) { this.name = theName; } } class Rhino extends Animal { constructor() { super("Rhino"); } } class Employee { private name: string; constructor(theName: string) { this.name = theName; } } let animal = new Animal("Goat"); let rhino = new Rhino(); let employee = new Employee("Bob"); animal = rhino; / / correct. Private animal = employee; // error: Animal is incompatible with Employee.Copy the code
3. Protected
It can only be accessed within the class that declares it and within subclasses (derived classes).
class Person { protected name: string; constructor(name: string) { this.name = name; } } class Employee extends Person { private department: string; constructor(name: string, department: string) { super(name) this.department = department; } public getElevatorPitch() {return 'Hello, my name is ${this.name} and I work in ${this.department}.'; } } let howard = new Employee("Howard", "Sales"); console.log(howard.getElevatorPitch()); console.log(howard.name); / / error; It can only be accessed in declared classes and subclassesCopy the code
When a constructor is marked protected, it cannot be instantiated, but it can be inherited
class Person { protected name: string; protected constructor(theName: string) { this.name = theName; Employee extends Person {private department: string; constructor(name: string, department: string) { super(name); this.department = department; } public getElevatorPitch() { return `Hello, my name is ${this.name} and I work in ${this.department}.`; } } let howard = new Employee("Howard", "Sales"); let john = new Person("John"); // Error: the constructor for 'Person' is protected.Copy the code
3. Readonly modifier
1. Read-only 2. Must be initialized in a declaration or constructor
class Octopus { readonly name: string; readonly numberOfLegs: number = 8; constructor (theName: string) { this.name = theName; } } let dad = new Octopus("Man with the 8 strong legs"); dad.name = "Man with the 3-piece suit"; / / error! Name is read-only.Copy the code
Constructor parameter properties
A constructor parameter defines and initializes a member
Class Octopus {// This code is equivalent to the preceding code readOnly numberOfLegs: Number = 8; constructor (readonly name: string) { } }Copy the code
4. Accessors (GET /set)
Accessors that have only GET but no set are automatically inferred as readonly
let passcode = "secret passcode"; 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 = "Bob Smith"; if (employee.fullName) { alert(employee.fullName); }Copy the code
5. The static attribute is static
Access directly through the class
class Grid { static origin = {x: 0, y: 0}; calculateDistanceFromOrigin(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; } constructor (public scale: number) {}} let grid1 = new Grid(1.0); // 1x scale let grid2 = new Grid(5.0); // 5x scale console.log(grid1.calculateDistanceFromOrigin({x: 10, y: 10})); console.log(grid2.calculateDistanceFromOrigin({x: 10, y: 10}));Copy the code
6. Abstract class
The abstract:
- Defining abstract classes (abstract classes cannot be instantiated)
- Define an abstract method inside an abstract class (contains no concrete implementation and must be implemented in a derived class)
The abstract application:
MakeSound (): void; makeSound(): void; // Move (): void {console.log(' Roaming the earch... '); }}Copy the code
Example:
abstract class Department { constructor(public name: string) { } printName(): void { console.log('Department name: ' + this.name); } abstract printMeeting(): void; } class AccountingDepartment extends Department { constructor() { super("Accounting and Auditing"); } printMeeting(): void { console.log('The Accounting Department meets each Monday at 10am.'); } generateReports(): void { console.log('Generating accounting reports... '); } } let department: Department; // Define the type of variable department = new department (); // ❌ cannot be instantiated department = new AccountingDepartment(); department.printMeeting(); department.printName(); department.generateReports(); The ❌ method declaration does not exist in the abstract classCopy the code
6. Advanced technique – constructors
When you declare a class in TS, you declare both the instance type and the constructor.
class Greeter {
greeting: string;
constructor(message: string) {
this.greeting = message;
}
greet() {
return "Hello, " + this.greeting;
}
}
let greeter: Greeter;
greeter = new Greeter("world");
console.log(greeter.greet());
Copy the code
The result of compiling to javascript is as follows:
var Greeter = (function() {
function Greeter(message) {
this.greeting = message;
}
Greeter.prototype.greet = function() {
return "Hello, " + this.greeting;
}
return Greeter
}());
var greeter;
greeter = new Greeter("world");
console.log(greeter.greet());
Copy the code