TypeScrip Class类

示例代码:

//定义类
class Person {
    constructor () {
 
    }
    run () {
        
    }
}

在TypeScript是不允许直接在constructor 定义变量的 需要在constructor上面先声明 如果了定义了变量不用 也会报错 通常是给个默认值 或者 进行赋值

class Person {
    name:string
    age:number = 0
    bol:boolean
    constructor(name:string, age: number, bol: boolean) {
        this.name = name
        // this.age = age
        this.bol = bol
    }
}

new Person('zs', 18 , false)

类的修饰符 public、 private、 protected 和 static 静态属性 和 静态方法

public 修饰符 可以让你定义的变量 内部访问 也可以外部访问 如果不写默认就是public
private 修饰符 代表定义的变量私有的只能在内部访问 不能在外部访问
protected 修饰符 代表定义的变量私有的只能在内部和继承的子类中访问 不能在外部访问
static 定义的属性 不可以通过this 去访问 只能通过类名去调用
static 静态函数 同样也是不能通过this 去调用 也是通过类名去调用

class Person1 {
    public name:string //使用public 修饰符 可以让你定义的变量 内部访问 也可以外部访问 如果不写默认就是public
    private age:number // 使用  private 修饰符 代表定义的变量私有的只能在内部访问 不能在外部访问
    protected bol:boolean //使用  protected 修饰 符 代表定义的变量私有的只能在内部和继承的子类中访问 不能在外部访问
    static aaa:string = '123456' // 静态属性 我们用static 定义的属性 不可以通过this 去访问 只能通过类名去调用 (Person1.aaa)
    constructor(name:string, age: number, bol: boolean) {
        this.name = name
        this.age = age
        this.bol = bol
    }
    // static 静态函数 同样也是不能通过this 去调用 也是通过类名去调用
    static run () {
        this.aaa
        return this.aaa1()
    }

    static aaa1() {
        return 'skjdfbnoidfb'
    }

}

new Person1('zs', 18 , false)

console.log(Person1.run())

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 () {
 
    }
}

抽象类

我们在A类定义了 getName 抽象方法但为实现
我们B类实现了A定义的抽象方法 如不实现就不报错 我们定义的抽象方法必须在派生类实现

abstract class N {
    name:string
    constructor(name:string) {
        this.name = name
    }
    setName(name:string) {
        this.name = name
    }
    abstract getName():string

}

class M extends N {
    constructor() {
        super('zs')
    }
    getName():string {
        return this.name
    }
}

let q = new M()
q.setName('zs1')
q.getName()
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值