1. class Person{
  2. name:string;
  3. age:number;
  4. constructor(name: string, age:number) {
  5. this.name = name;
  6. this.age = age;
  7. }
  8. print() {
  9. return this.name + ':' + this.age;
  10. }
  11. }
  12. const p = new Person('Tom', 30);
  13. p.print(); // Tom: 30

继承

  1. class Amy {
  2. sayAge(age: number = 0) {
  3. console.log(`Amy age is ${age}`);
  4. }
  5. }
  6. class Ami extends Amy {
  7. sayLastName(){
  8. console.log('Vernon');
  9. }
  10. }
  11. const ami = new Ami();
  12. ami.sayLastName(); // Vernon
  13. ami.sayAge(20); // Amy age is 30

修饰符

  1. class Person {
  2. public name: string;
  3. private sex: string;
  4. protected age: number;
  5. constructor(name: string, sex: string, age:number){
  6. this.name = name;
  7. this.sex = sex;
  8. this.age = age;
  9. }
  10. }
  11. class Tom extends Person {
  12. constructor(name: string, sex: string, age: number){
  13. super(name, sex, age);
  14. }
  15. changeAge() {
  16. this.age = 40;
  17. }
  18. logSex() {
  19. console.log(this.sex);
  20. }
  21. }
  22. new Person('Tom', 'man', 30).name; //公有属性可以访问 -> tom
  23. new Person('Tom', 'man', 30).sex; // 私有属性 不允许在外部访问
  24. const t = new Tom('Tom', 'man', 30);
  25. t.changeAge(); //受保护的属性 不允许被修改
  26. t.logSex(); // 私有属性,不允许除自己类外的访问
  27. class Octopus {
  28. readonly name: string;
  29. readonly numberOfLegs: number = 8;
  30. constructor (theName: string) {
  31. this.name = theName;
  32. }
  33. }
  34. let dad = new Octopus("name");
  35. dad.name = "new name"; // 错误! name 是只读的.

public共有属性,可以随意访问。
private私有属性,只有自己的类可以访问。
protected受保护的属性,在类和子类中可以访问,其他地方无法访问。
readonly只读属性,只能读取。

存取器(拦截器)

  1. class Person {
  2. private name: string;
  3. get name(): string {
  4. return this.name;
  5. }
  6. set name(newName: string) {
  7. if (newName && newName == "new name") {
  8. this.name = newName;
  9. } else {
  10. console.log("Error: The new name doesn't conform to the rules");
  11. }
  12. }
  13. }
  14. const p = new Person();
  15. P.name = 'old name'; // 报错咯~

静态属性

  1. class Person {
  2. static age = 30;
  3. say() {
  4. console.log(this.age);
  5. }
  6. }
  7. console.log(Person.age); // 30;
  8. const p = new Person();
  9. console.log(p.age()); // 错误 静态属性只能有类名调用
  10. p.say(); // 错误 静态属性只能有类名调用

抽象类

抽象类是作为其他子类的基类,一般是不会被实例化,用abstract定义抽象方法 和抽象类。定义得抽象方法,子类必须实现,也可以由自身实现。

  1. abstract class Person {
  2. abstract say():void;
  3. abstract tell(name: string): void{
  4. console.log(`hello ${name}`);
  5. }
  6. }
  7. class Man extends Person {
  8. say(): void {
  9. console.log(`抽象类定义的,子类必须实现`);
  10. }
  11. }