ts 继承 访问父类的属性、方法 为什么要用this?

父类

import { baseUrl } from "../config/base";
import { HttpHelp } from "../utils/HttpHelp";

class BaseService {
  httpHelp: HttpHelp = new HttpHelp();
  baseUrl: string = baseUrl;
}
export { BaseService };

子类

import { BaseService } from "./BaseService";

class PublicService extends BaseService {
  public uploadimg(files: string) {
    this.httpHelp.uploadFile(this.baseUrl + "/common/upload", files).then(res => {
      console.info(res)
    })
  }
}
export { PublicService };

这里的子类调用父类的方法和属性用的this,而不是super,如果用super会提示找不到属性,找不到方法。请问,为什么?

阅读 2.7k
1 个回答

在TypeScript中,this 关键字用于表示当前类的实例。当你在一个类中继承另一个类时,子类将拥有父类的所有属性和方法。为了在子类中访问这些属性和方法,你需要使用 this 关键字。

在TypeScript中,super 关键字用于表示父类的实例。在子类中,你可以使用 super 关键字来调用父类的构造函数、属性和方法。

以下是一个示例:

class Animal {
  name: string;

  constructor(name: string) {
    this.name = name;
  }

  makeSound(): void {
    console.log("The animal makes a sound");
  }
}

class Dog extends Animal {
  constructor(name: string) {
    super(name);
  }

  makeSound(): void {
    super.makeSound(); // 调用父类的makeSound方法
    console.log("The dog barks");
  }

  printName(): void {
    console.log("The dog's name is " + this.name); // 访问父类的属性
  }
}

let dog = new Dog("Buddy");
dog.makeSound(); // 输出:The animal makes a sound 和 The dog barks
dog.printName(); // 输出:The dog's name is Buddy

在这个例子中,Dog 类继承了 Animal 类。在 Dog 类中,我们使用 super 关键字来调用父类的 makeSound 方法和构造函数。使用 this 关键字来访问父类的 name 属性。

总之,在TypeScript中,this 关键字用于访问当前类实例的属性和方法,而 super 关键字用于在子类中调用父类的构造函数、属性和方法。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题