美文网首页
typescript入门-类

typescript入门-类

作者: copyLeft | 来源:发表于2021-06-08 22:52 被阅读0次

类定义 class

class Car{}

实例化 new

const c = new Car()

实例属性、方法

class Car{
  // 实例属性
  color: string
  // 构造函数
  constructor(color: string) {
    // 设置实例属性
    this.color = color
  }
}


// 实例属性必须现在类中定义
class Car{
   constructor(color: string) {
    // Property 'msg' does not exist on type 'Car'.
    this.color = color
  }
}

继承 extends

class Car{
  // 实例属性
  color: string
  // 构造函数
  constructor(color: string) {
    // 设置实例属性
    this.color = color
  }
}


class MiniCar extends (Car) {


  // 子类属性
  size:number = 1.2
  
  constructor(color: string, size?:number) {
    // 父类属性
    super(color)
    this.size = size || 1.2
  }
}




const m = new MiniCar('red', 1.3)
console.log(m.size)
// 1.3

静态属性、方法

使用 static 前置标识静态属性或方法

class Car{
  
  static version:string = 'v1.0'
  static setVersion(v: string) {
    Car.version = v
  }
  
  color: string
  constructor(color: string) {
    this.color = color;
  }
}
// 静态属性、方法为了方便类无需实例化,直接调用相关属性和方法
// 静态属性、方法只存在于类定义中, 实例无法调用
console.log(Car.version)
Car.setVersion('v1.1')
console.log(Car.version)
// 1.0
// 1.1


const c = new Car('orange')
console.log(c.version)
//  Property 'version' does not exist on type 'Car'. Did you mean to access the static member 'Car.version' instead?

私用属性、方法

private

只存在于当前类内的私用属性、方法

class Car{
  // 私有属性
  private factoryInfo:string = '...info'
  // 私有方法
  private writeFactoryInfo(msg: string) {
    this.factoryInfo = msg
  }
  
  color: string
  constructor(color: string) {
    this.color = color;
  }


  readFactoryInfo() {
    // 使用属性、方法只能在类内部使用
    return this.factoryInfo
  }
}




const c = new Car('orange')
console.log(c.readFactoryInfo())


// private 私有属性不能被子类继承或直接调用
class MiniCar extends Car{
  constructor(color: string) {
    super(color)
    this.writeFactoryInfo('mini car')
    // Property 'writeFactoryInfo' is private and only accessible within class 'Car'.
  }
}

protected

于 private 类似, 但子类可继承、调用父类私有属性、函数

class Car{
  // 私有属性
  protected factoryInfo:string = '...info'
  // 私有方法
  protected writeFactoryInfo(msg: string) {
    this.factoryInfo = msg
  }
  
  color: string
  constructor(color: string) {
    this.color = color;
    this.writeFactoryInfo('prototype car')
  }




  readFactoryInfo() {
    // 使用属性、方法只能在类内部使用
    return this.factoryInfo
  }
}




class MiniCar extends Car{
  constructor(color: string) {
    super(color)
    this.writeFactoryInfo('mini car')
  }
}


const m = new MiniCar('red')


console.log(m.readFactoryInfo())
// mini car

getter、 setter

class Car{
  private _version:string = ''


  get version(): string{
    console.log('get version')
    return this._version
  }


  set version(v: string) {
    console.log('set version')
    this._version = v
  }
  
}


const c = new Car()
c.version = 'v2.0'
console.log(c.version)


// set version
// get version
// v2.0

相关文章

网友评论

      本文标题:typescript入门-类

      本文链接:https://www.haomeiwen.com/subject/utaleltx.html