首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >TypeScript的继承(二)

TypeScript的继承(二)

原创
作者头像
堕落飞鸟
发布2023-05-22 10:00:58
发布2023-05-22 10:00:58
4170
举报
文章被收录于专栏:飞鸟的专栏飞鸟的专栏

方法重写

派生类可以重写基类的方法,即在派生类中定义与基类中同名的方法。通过方法重写,派生类可以修改基类方法的实现,以适应自身的需求。

代码语言:javascript
复制
class Animal {
  speak() {
    console.log("Animal is speaking.");
  }
}

class Dog extends Animal {
  speak() {
    console.log("Dog is barking.");
  }
}

在上面的例子中,Dog 类重写了 Animal 类的 speak 方法,并修改了方法的实现。

访问基类的方法

在派生类中,可以使用 super 关键字来访问基类的方法。

代码语言:javascript
复制
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 运算符来检查一个对象是否是某个类的实例。

代码语言:javascript
复制
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 类的实例。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 方法重写
  • 访问基类的方法
  • instanceof 运算符
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档