Fork me on GitHub

TypeScript 类和继承

class 创建类

class city{
  //成员变量
  name:string;
  age:number;
 // 构造函数 实例化类的时候触发方法
  constructor(name:string,age:number){
    this.name = name;
    this.age = age
  }
  //方法
  about(){
    console.log('name:' + this.name);
    console.log('age:' + this.age);
  }
}
//创建对象
let ct = new city('城市',2020);
console.log(ct.name)
ct.about()

 

 继承

class Person {
  name:string;
  constructor(name:string){
    this.name = name;
  }
  run():string{
    return this.name;
  }
}

class Web extends Person{
  constructor(name:string){
    super(name)       /*初始化父类的构造函数*/
  }
  work():string{
    return this.name + '在工作';
  }
}
let a = new Web('李雷');
alert(a.run());
alert(a.work());

子类继承父类的时候,既可以继承父类的属性和方法,也可以自己创建新的方法;当子类的方法和父类重复时,优先实现子类的方法;

 

posted @ 2020-07-06 17:53  `A+  阅读(206)  评论(0编辑  收藏  举报