温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

TypeScript中的super关键字如何使用

发布时间:2024-07-09 13:40:06 来源:亿速云 阅读:115 作者:小樊 栏目:编程语言

在 TypeScript 中,super 关键字用于调用父类的方法或属性。在子类中,通过super关键字可以调用父类的构造函数、普通方法和静态方法。

  1. 调用父类的构造函数:
class Animal {
  constructor(name: string) {
    console.log(`An animal named ${name} is created`);
  }
}

class Dog extends Animal {
  constructor(name: string) {
    super(name);
    console.log(`A dog named ${name} is created`);
  }
}

const myDog = new Dog("Buddy");
  1. 调用父类的普通方法:
class Animal {
  sound(): void {
    console.log("Animal makes sound");
  }
}

class Dog extends Animal {
  sound(): void {
    super.sound();
    console.log("Dog barks");
  }
}

const myDog = new Dog();
myDog.sound();
  1. 调用父类的静态方法:
class Animal {
  static type(): void {
    console.log("This is an animal");
  }
}

class Dog extends Animal {
  static type(): void {
    super.type();
    console.log("This is a dog");
  }
}

Dog.type();

总之,super关键字用于访问父类的方法和属性,可以在子类的构造函数、普通方法和静态方法中使用。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI