类
class Greeter {
greeting: string;
constructor(message: string) {
this.greeting = message;
}
greet() {
return "Hello, " + this.greeting;
}
}
let greeter = new Greeter("world");
上面等同于原生js
function Greeter(message) {
this.greeting = message;
}
Greeter.prototype.greet = function () {
return "Hello, " + this.greeting;
};
继承
class A extends B
,A类继承B类所有的属性和方法
class Animal {
name: string;
constructor(theName: string) { this.name = theName; }
move(distanceInMeters: number = 0) {
console.log(`Animal moved ${distanceInMeters}m.`);
}
}
class Dog extends Animal {
constructor(name: string) { super(name); }
bark() {
console.log('Woof! Woof!');
}
}
const dog = new Dog();
dog.bark();
dog.move(10);
dog.bark();
子类通过 super
调用父类的成员
修饰符
修饰符定义了成员变量的作用域范围
public
: 外部可以修改类成员
private
: 仅在类内部可访问
protected
: 子类可访问
readonly
: 只读属性,必须在声明或构造函数里被初始化
参数属性
给参数增加以上修饰符,可自动生成同修饰符的内部变量
class Octopus{
readonly name: string;
constructor( theName: string) {
this.name = theName
}
}
可以简化为以下写法,ts会自动生成上面效果的代码
class Octopus{
constructor( readonly name: string) {
}
}
public, private ,protected
也适用上面的简化写法
存取器
在获取内部属性值时,通过存取器代替直接存储。可增加中间的拦截逻辑
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);
}
以上例子在用户设置类属性值前,做了逻辑判断
静态属性
普通类成员都是定义在prototype上的实例成员,当类通过new
操作符被实例化时可用。ts通过static
关键字可申明直接定义在类上的成员,所有实例对象共享,亦可通过类名直接单独调用
class Counter {
static counter = 0;
add() {
Counter.counter++
console.log(Counter.counter)
}
}
let counter1 = new Counter()
let counter2 = new Counter()
counter1.add() // counter = 1
counter2.add() // counter = 2
Counter.counter++ // counter = 3
抽象类
abstract
定义一个抽象类及抽象类内部的抽象方法。抽象类不能直接实例化,必须通过子类实现抽象方法后实例化子类。
抽象类目的在于提取共有特性,也可以包含部分函数实现。
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'); // 在派生类的构造函数中必须调用 super()
}
printMeeting(): void {
console.log('The Accounting Department meets each Monday at 10am.');
}
generateReports(): void {
console.log('Generating accounting reports...');
}
}
let department: Department; // 允许创建一个对抽象类型的引用
department = new Department(); // 错误: 不能创建一个抽象类的实例
department = new AccountingDepartment(); // 允许对一个抽象子类进行实例化和赋值
department.printName();
department.printMeeting();
department.generateReports(); // 错误: 方法在声明的抽象类中不存在
···
网友评论