typescript学习(2)

类的定义与继承

// 类的定义
class Person{
  name='lui';
  getName(){
    return this.name
  }
}

// 类的继承
class Student extends Person{
  getStudentName(){
    return 'stu lulu'
  }
  // 多态
  getName(){
    // super:子类把父类方法覆盖之后,使用super来使用父类的方法
    return  super.getName()+' liu'
  }
}
const stu = new Student()
console.log(stu.getName())
console.log(stu.getStudentName())

类的访问类型与构造器

类的访问类型:private,protected,public

  • public是默认类型,运行在类的内外被调用
  • private只允许在类内被调用
  • protected 允许在类内及继承的子类中使用
class Person{
  protected name:string; // 默认类型 public
  sayHi(){ //默认类型 public
    this.name;
    console.log('hi')
  }
}
class Students extends Person{
  public sayBye(){
    this.name
  }
}

构造器 constructor

  • 传统语法与简写语法

new实例的时候,constructor自动执行

class Person{
  // 传统写法
  public name:string;
  // new实例的时候,constructor自动执行
  constructor(name:string){
    this.name = name
  }

  // 简化写法
//   constructor(public name:string){}
// }
// const person = new Person('lui')
// console.log(person.name)

  • 继承必须实现super
class Person{
  constructor(public name:string){}
}
class Student extends Person{
  constructor(public age:number){
    super('lui') //调用父类的构造函数
    // super在继承时,必须调用
  }
}
const student = new Student(22)
student.age

静态属性:Setter和Getter

// getter & setter
class Person{
  constructor(private _name:string){}
  get name(){ //通过getter把私有属性给用户
    return this._name + 'liu'
  }
  set name(name:string){
    this._name = name
  }
}

const person = new Person('lui')
console.log(person.name)
person.name ='lulu'
console.log(person.name)

单例模式用typescript实现

class Demo{
  private static instance:Demo;
  private constructor(public name:string){
    // 不允许通过new来创建实例
  }
  static getInstance(){
    if(!this.instance){
      this.instance = new Demo('lui')
    }
    return this.instance
  }
}
// demo1 和 demo2是一个实例,完全相同
const demo1 = Demo.getInstance();
const demo2 = Demo.getInstance();
console.log(demo1.name)
console.log(demo2.name)

抽象类

// readonly修饰器:只能读不能改
class Person{
  public readonly _name:string;
  constructor(name:string){
    this._name= name
  }
  get name(){
    return this._name;
  }
}
const person = new Person('lui')
// 抽象类只能被继承,不能被实例化
// 抽象方法必须被子类实现
abstract class Geom{
  width:number;
  getType(){
    return 'Geom'
  }
  abstract getArea():number;
}

class Circle extends Geom{
  getArea(){
    return 134;
  }
}
class Square{}

interface 与interface继承

interface Person{
  name:string;
}
interface Teacher extends Person{
  // name:string;
} 
interface Student  extends Person{
  // name:string;
  age:number;
}
const student = {
  name:'lui'
}
const teacher ={
  name:'li',
  age:99
}
const getUserInfo=(user:Person)=>{
  console.log(user.name)
}
getUserInfo(student)
getUserInfo(teacher)
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容