TypeScript学习(三)—— 类

前篇:TypeScript学习(二)—— 函数

js中的类可以看之前写的:new操作符到底干了什么

接下来说说TypeScript中的class。在TS中class的定义方式和es6中的语法糖class很相似。

定义class

class A {
    name:string //声明name是string类型,省略了public
    constructor(name:string){
        this.name = name
    }
    run():void {        //定义A.prototype上的run方法
        console.log(this.name)
    }
    getName():string{
        return this.name
    }
    setName(name:string):void{
        this.name = name
    }
}
const a = new A() //没给默认值不传参数会报错
const a = new A('汪汪!') //没给默认值不传参数会报错
a.run() //汪汪!
a.setName('咪咪!')
console.log(a.getName()) //'咪咪'
复制代码

class的继承

class Animal {  //定义父类
    name:string
    constructor(name:string){
        this.name = name
    }
    sayName():void{
        console.log(`i am ${this.name}`)
    }
}
class Cat extends Animal{ //定义个继承父类的子类
    call:string
    constructor(name:string, call:string = 'mimimi!'){  //如果和Animal中构造函数传入的name类型不同就会报错
        super(name)         //作用是把this传到父类,调用父类构造函数
        this.call = call
    }
    sayCall():void{
        console.log(`我是${this.name},我的叫声是:${this.call}`)
    }
}
const cat = new Cat('咪咪', '喵喵')
cat.sayName() //i am 咪咪
cat.sayCall() //我是咪咪,我的叫声是:喵喵
复制代码

类里面的修饰符

public:公有属性,在类里面、子类、类外面都可以访问

protected:保护类型,在类里面、子类里面可以访问,在类外部没法访问

private:私有属性,在类里面可以访问,子类和类外部无法访问

如果不写默认为public。(其实只是代码检测会报错,编译成es5后都可以访问得到)

//public
class Animal {
    public name:string
...
    sayName():void{
        console.log(`i am ${this.name}`) //类里面可以访问
    }
}
class Cat extends Animal{
...
    sayCall():void{
        console.log(`我是${this.name},我的叫声是:${this.call}`) //子类中可以访问
    }
}
const animal = new Animal('dog')
console.log(animal.name) //类外面可以访问

//protected
class Animal {
    protected name:string
...
    sayName():void{
        console.log(`i am ${this.name}`) //类里面可以访问
    }
}
class Cat extends Animal{
...
    sayCall():void{
        console.log(`我是${this.name},我的叫声是:${this.call}`) //子类中可以访问
    }
}
const animal = new Animal('dog')
console.log(animal.name) //编译器报错,类外面访问不到

//private
class Animal {
    private name:string
...
    sayName():void{
        console.log(`i am ${this.name}`) //类里面可以访问
    }
}
class Cat extends Animal{
...
    sayCall():void{
        console.log(`我是${this.name},我的叫声是:${this.call}`) //编译器报错,子类中访问不到
    }
}
const animal = new Animal('dog')
console.log(animal.name) //编译器报错,类外面访问不到
复制代码

类中的静态属性和静态方法

class Animal {
...
    static SF():void{ //定义静态方法
        console.log(this.SP)
    }
    static SP:string = '我是静态属性'  //定义静态属性,不建议定义静态属性
}
Animal.SF() // =》我是静态属性  静态方法是在类上调用的方法,方法中的this指向Animal本身
console.log(Animal.SP) // =》我是静态属性
复制代码
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值