创建类:class关键字
//age为number类型//sex为string类型class person{age:numbersex: "男"}//person的实例对象p的类型是personconst p = new person()
构造函数:constructor关键字
一个类只可以有一个constructor方法,且不写会调用默认的构造函数
//构造函数不需要返回值类型class person{age: numbersex: stringconstructor(age: number,sex: string){this.age=agethis.sex=sex}}//调用函数const p = new person(18,"男")
类的实例方法
//定义一个取平方的方法class point {x=10y=20scale(n:number):void{this.x*=nthis.y*=n}}//调动函数const p = new point()p.scale(10)
类的继承
在JS中只有extends,而TS新增了implements
extends方法
//定义动物类class Animal{move(){console.log('moving')}}//定义狗类并继承动物类class Dog extends Animal{bark(){consple.log('汪')}}//狗类具有move()和bark()方法const dog = new Dog()dog.move()//movingdog.dark()//汪
implements方法(实现)
实现接口,可以大致理解为继承接口,使用此方法后类中必须指定所有的方法和属性
//定义接口interface singale{string():voidname:string}//类中实现接口class person implements singale{name='jack'sing(){console.log('我是个沉默不语的,靠着墙壁晒太阳的过客')}}//调用const p = new person()console.log(p.name+"在唱"+p.sing())
可见性修饰符
public
在任何地方都可以被访问到(默认为public)
//动物类class Animal{public move(){console.log('走两步')}}const a = new Animal()a.move()//输出 走两步//狗继承class Dog extends Animal{bark(){this.move()console.log('汪')}}const d = new dogd.bark()//输出 走两步 汪d.move()//输出 走两步
protected
在声明类中或子类可以访问,子类可以通过this来访问父类受保护的成员,但是实例不可以访问
//动物类class Animal{protected move(){console.log('走两步')}run(){this.move()console.log('跑起来')}}const a = new Animal()a.move()//报错,不可在实例对象中访问受保护的成员a.run()//输出走两步 跑起来//狗继承//调用bark()函数输出 走两步 跑起来 汪class Dog extends Animal{bark(){this.move()console.log('汪')}}const d = new dogd.bark()//输出 走两步 跑起来 汪d.run()//输出走两步 跑起来d.move()//报错
private
只在当前类可见,其他都不可访问
//动物类class Animal{private move(){console.log('走两步')}}const a = new Animal()a.move()//报错,不可在实例对象中访问私有的成员//狗继承class Dog extends Animal{bark(){//this.move()//报错 不可在子类访问父类私有成员console.log('汪')}}const d = new dogd.move()//报错
