方法重写
派生类可以重写基类的方法,即在派生类中定义与基类中同名的方法。通过方法重写,派生类可以修改基类方法的实现,以适应自身的需求。
代码语言:javascript复制class Animal {
speak() {
console.log("Animal is speaking.");
}
}
class Dog extends Animal {
speak() {
console.log("Dog is barking.");
}
}在上面的例子中,Dog 类重写了 Animal 类的 speak 方法,并修改了方法的实现。
访问基类的方法
在派生类中,可以使用 super 关键字来访问基类的方法。
class Animal {
speak() {
console.log("Animal is speaking.");
}
}
class Dog extends Animal {
speak() {
super.speak(); // 调用基类的 speak 方法
console.log("Dog is barking.");
}
}在上面的例子中,Dog 类的 speak 方法使用 super.speak() 来调用 Animal 类的 speak 方法。
instanceof 运算符
在 TypeScript 中,我们可以使用 instanceof 运算符来检查一个对象是否是某个类的实例。
class Animal {}
class Dog extends Animal {}
const animal = new Animal();
const dog = new Dog();
console.log(animal instanceof Animal); // 输出: true
console.log(dog instanceof Animal); // 输出: true
console.log(dog instanceof Dog); // 输出: true在上面的例子中,我们使用 instanceof 运算符检查 animal 是否是 Animal 类的实例,以及 dog 是否是 Animal 类和 Dog 类的实例。


