TypeScript学习总结(9)

class类

一、class的基本使用

class Person { 
    age: number
    name: string
}
const person = new Person()

根据 TS 中的类型推论,可以知道Person类的实例对象p的类型是Person。
TS 中的 clas5,不仅提供了 class 的语法功能,也作为一种类型存在。

二、class的构造函数 

构造函数的作用是为类的实例属性设置初始值

class Person { 
    age: number
    name: string
    constructor(age: number, name: string) {
        this.age = age
        this.name = name
    }
}
const person = new Person(20, "John")
console.log(person.name)
console.log(person.age)

 成员初始化(比如,age:number)后,才可以通过this.age来访问实例成员。
需要为构造函数指定类型注解,否则会被隐式推断为 any;构造函数不需要返回值类型

三、class的实例方法 

class point {
    x = 10
    y = 20
    scale(n: number) {
        this.x *= n
        this.y *= n
        
    }
}
const p = new point()
p.scale(2)
console.log(p.x, p.y)

 方法的类型注解(参数与返回值)与函数用法相同

四、class的继承

 类继承的两种方式:1.extends(继承父类)2.implements(实现接口)。

1.extends继承

class Animal {
    move() {
        console.log("Moving")
    }
}
class Dog extends Animal {
    bark() {
        console.log("Barking")
    }
}
const dog = new Dog()
dog.bark()
dog.move()

通过extends关键字实现继承

子类Dog继承父类Animal,则Dog的实例对象dog就同时具备了父类Animal和子类Dog的所有属性和方法

2.implements继承

interface sing{
    sing(): void
}
class Person implements sing {
    sing() {
        console.log("Singing")
     }
}
const person = new Person()
person.sing()

 通过 implements 关键字让 class 实现接口。
Person 类实现接口 sing 意味着,Person类中必须提供sing 接口中指定的所有方法和属性

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值