前篇:
js中的类可以看之前写的:。
接下来说说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后都可以访问得到)
//publicclass 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) //类外面可以访问//protectedclass 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) //编译器报错,类外面访问不到//privateclass 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) // =》我是静态属性复制代码