TypeScript(8Class)

94 阅读1分钟

描述Class

class Person {
  name: string
  age: number
  sub: boolean = true //👇没有用到可以给个默认值
  constructor(name: string, age: number, sub: boolean) {
    this.name = name
    this.age = age
    // this.sub = sub
  }
}

const obj2 = new Person('Durant', 39, true)

Class的修饰符

总共有三个 public private protected

  1. public 属性内部外部都能访问(默认)
  2. private 私有变量只能在内部访问
  3. protected 内部和子类是可以访问的
class Person {
  public name: string
  private age: number
  protected sub: boolean = true //👇没有用到可以给个默认值
  constructor(name: string, age: number, sub: boolean) {
    this.name = name
    this.age = age
    // this.sub = sub
  }
}

class Child extends Person {
  constructor() {
    super('Durant', 39, true)
    this.sub = true //protected 是可以访问的
  }
}

const obj2 = new Person('Durant', 39, true)
console.log(obj2.age)  //外部不能访问

静态属性 static

class Person {
  public name: string
  static age: number  //静态属性
  protected sub: boolean = true
  constructor(name: string, age: number, sub: boolean) {
    this.name = name
    this.age = age
    // this.sub = sub
    ❌ 同样也调用不了 this.run()
    Person.run()  //是可以的
  }
  static run() {
      this.age = 89//静态方法是不能访问上面的变量的 
  }
  static dev() {
      this.run()
      this.age = 89//静态方法是不能访问上面的变量的 
  }
}
console.log(Person.age)  //不需要new了 直接通过累名就可以访问
console.log(Person.run())  //不需要new了 直接通过累名就可以访问

两个静态方法是可以通过this相互调用的 *可以访问Class的参数但不能访问constructor内部的变量

通过interface 描述 Class

interface Sound {
  run(type: boolean): void
}
interface Dd {
  build(): string
}

class Home implements Sound, Dd {
  run(val: boolean) {
  
  }
  build(): string {
    return 'Durant'
  }
}

同样可以继承

interface Sound {
  run(type: boolean): void
}
interface Dd {
  build(): string
}

class A {
  params: string
  constructor(params: string) {
    this.params = params
  }
}
class Home extends A implements Sound, Dd {
  run(val: boolean) {
  
  }
  build(): string {
    return 'Durant'
  }
}