构造函数.png
ts类.png

  1. // 1. 类 class
  2. class City {
  3. // 成员变量
  4. // cName: string = '';
  5. // cLevel: number = 1;
  6. cName: string;
  7. cLevel: number;
  8. // 构造函数
  9. constructor(name: string, level: number) {
  10. this.cName = name;
  11. this.cLevel = level;
  12. }
  13. // 成员方法
  14. about() {
  15. console.log(`Welcome to ${this.cName}, Level is ${this.cLevel}`);
  16. }
  17. }
  18. // 创建对象
  19. let c1 = new City('P城', 5);
  20. console.log(c1.cName);
  21. c1.about();
  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. getName():void{
  9. console.log(this.name);
  10. }
  11. }
  12. var p:Person = new Person("cheng",20);
  13. p.getName();
  1. ## 当没有构造函数的时候,代码底层有自动补全构造函数
  2. class Person{
  3. /* 实例的name */
  4. name:string
  5. age:number
  6. getName():void{
  7. console.log(this.name);
  8. }
  9. }
  10. var p:Person = new Person();
  11. p.getName();

static

  1. //static修饰的变量是类所共有的,只能通过类名去调用。
  2. class Person{
  3. /* 实例的name */
  4. static skill:string = "js";
  5. name:string
  6. age:number
  7. getName():void{
  8. console.log(Person.skill)
  9. console.log(this.name);
  10. }
  11. }
  12. var p:Person = new Person();
  13. p.getName();