Typescript 中的类的应用

类的创建

class Person {
  // 属性
  name: string;
  age: number;
  // 构造函数
  constructor(name:string, age:number) {
    this.name = name;
    this.age = age;
  }
  // 方法
  print() {
    console.log('name: ' + this.name + ' age: ' + this.age);
  }
}

var p = new Person('Joh', 90);
p.print();

类的继承

class Human {
  name: string;
  age: number;
  tell() {
    return this.name + ' ' + this.age;
  }
}

// Student 继承自 Human
class Student extends Human {
  school: string;
  // 此处Student 也必须传递构造方法
  tell() {
    return this.name + ' ' + this.age + ' ' + this.school;
  }
}

var s = new Student();
s.name = 'Joh';
s.age = 90;
s.school = 'MIT';

console.log(s.tell());

使用super关键字继承属性

class Human {
  name: string;
  age: number;
  constructor(name: string, age:number) {
    this.name = name;
    this.age = age;
  }
  tell() {
    return this.name + ' ' + this.age;
  }
}

// Student 继承自 Human
class Student extends Human {
  school: string;
  // 此处Student 也必须传递构造方法
  constructor(school: string) {
    this.school = school;
    super('Joh', 90);
  }
  tell() {
    return this.name + ' ' + this.age + ' ' + this.school;
  }
}

var ss = new Student('MIT');

console.log(s.tell());

类的访问修饰符

class People {
  // public 是默认的, 不加修饰符都是public
  public name:string;
  age:number;
  // private 无法访问和继承
  private color:string;

  getInfo() {
    return this.name + ':' + this.age;
  }
}

class Teacher extends People {
  school:string;
  getInfo() {
    return this.name + ':' + this.age + ':' + this.school;
  }
}

var t = new Teacher();
t.name = 'Joh';
t.age = '90';
t.school = 'MIT';
console.log(t.getInfo());

在constructor中也可添加修饰符

class People {
  // 如下所示
  constructor(public height: number){
  }
}

封装

通过 getter 和 setter 方法来设置

class Hello {
  name:string;
  // 私有的 _age属性
  private _age:number;
  // 普通方法
  tell() {
    return this.name;
  }
  // getter 和 setter 来访问和设置私有方法, 为外部提供一个接口来使用
  get name():string{
    return this._name;
  }

  set name(n:string){
    this._name = n;
  }
}

var h = new Hello():
h.name = 'Joh';
console.log(h.tell());

关键词 static

class Person {
  name:string;
  // 静态属性或方法 需要使用类名来调用
  static age:string;
  tell() {
    alert('Name: ' + this.name);
  }
  getInfo() {
    return 'Name: ' + this.name + ' ' + 'Age' + this.age;
  }
}

var p = new Person();
p.name = 'Joh';
Person.age = 90;
p.tell();
console.log(p.getInfo());

自定义类是一种引用数据类型

class Greeter {
  greeting:string;
  constructor(message: string) {
    this.greeting = message;
  }

  greet() {
    return 'Hello, ' + this.greeting;
  }
}

var gr:Greeter; // 此处声明gr为Greeter的类型
gr = new Greeter(); // 此处实例化赋值
console.log(gr.greet('Joh'));

猜你喜欢

转载自blog.csdn.net/Tyro_java/article/details/81073271