类表达式和一般的类很像,唯一的区别就是不需要名字,可以直接把表达式赋给一个变量。
const myClass = class {
constructor(public name: string) {}
}
const t = new myClass('abc');
console.log(t);
console.log(t.name);
添加abstract关键字用于定义抽象类和成员函数。
抽象类就是有些方法没有实现,需要在子类里面实现。所以抽象类不能实例化,只能用完全实现抽象方法的子类来实例化对象。
abstract class Base {
abstract getName(): string;
printName() {
console.log(this.getName());
}
}
class Derived extends Base {
getName(): string {
return 'Derived';
}
}
const t = new Derived();
t.printName();
通过使用构造函数签名,可以防止传入一个抽象类。
abstract class Base {
abstract getName(): string;
printName() {
console.log(this.getName());
}
}
class Derived extends Base {
getName(): string {
return 'Derived';
}
}
function greet(ctor: new () => Base) {
const t = new ctor();
t.printName();
}
greet(Base);
如果传入的Base类(抽象类),编译器就会报错。
使用greet(Derived)。代码就能正常运行。
留言与评论(共有 0 条评论) “” |