TypeScrip5

类的修饰符

继续昨天的知识点,class类

总共有三个 public private protected

使用public 修饰符 可以让你定义的变量 内部访问 也可以外部访问 如果不写默认就是public

class Person{
   public name: string
   age: number
   color:string
   constructor(name,age){
      this.name = name
      this.age = age
      this.color = color
   }
   run() {
   }
}

let people = new Person('wang',18,'red')
people.name

使用  private 修饰符 代表定义的变量私有的只能在内部访问 不能在外部访问

class Person{
   public name: string
   private age: number
   color:string
   constructor(name,age){
      this.name = name
      this.age = age
      this.color = color
   }
   run() {
   }
}

let people = new Person('wang',18,'red')
people.age // 这样会报错,不能这样写

 使用  protected 修饰符 代表定义的变量私有的只能在内部和继承的子类中访问 不能在外部访问

class Person {
    public name:string
    private age:number 
    protected color:string
    constructor (name:string,ages:number,some:string) {
       this.name = name
       this.age = ages
       this.color = color
    }
    run () {
 
    }
}
 
class Man extends Person{
    constructor () {
        super("wang",18,'red')
        console.log(this.color)
    }
    create () {
       console.log(this.color)
    }
}
let people = new Person('wang',18,'red')
let man = new Man()
man.color

static 静态属性 和 静态方法

我们用static 定义的属性 不可以通过this 去访问 只能通过类名去调用

class Person{
   public name: string
   private age: number
   static color:string
   constructor(name,age){
      this.name = name
      this.age = age
      this.color = color // 这样会报错
   }
   run() {
   }
}

Person.color // 这样没有问题

static 静态函数 同样也是不能通过this 去调用 也是通过类名去调用,如果两个函数都是static 静态的是可以通过this互相调用。

interface 定义 类

 interface 定义类 使用关键字 implements   后面跟interface的名字多个用逗号隔开 继承还是用extends

 
interface PersonClass {
    get(type: boolean): boolean
}
 
interface PersonClass2{
    set():void,
    asd:string
}
 
class A {
    name: string
    constructor() {
        this.name = "123"
    }
}
 
class Person extends A implements PersonClass,PersonClass2 {
    asd: string
    constructor() {
        super()
        this.asd = '123'
    }
    get(type:boolean) {
        return type
    }
    set () {
 
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值