Class类
定义类
1 2 3 4 5 6 7 8 9
| class Person { name:string; age:number; constructor(name:string, age:number) { this.name = name; this.age = age } } let person:Person = new Person('lwh',18)
|
类内部定义的变量,必须初始化或在内部赋值
类的修饰符
public
、private
、protected
1 2 3 4 5 6 7 8 9 10
| class Person { public name:string; private age:number; protected like:any; constructor(name:string, age:number, like?:any) { this.name = name; this.age = age; this.like = like; } }
|
- 使用public 修饰符 可以让你定义的变量 内部访问 也可以外部访问 如果不写默认就是public
- 使用 private 修饰符 代表定义的变量私有的只能在内部访问 不能在外部访问
- 使用 protected 修饰符 代表定义的变量私有的只能在内部和继承的子类中访问 不能在外部访问
static静态属性和静态方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| class Person { public name:string; private age:number; protected like:any; public static race:string = 'homo'; constructor(name:string, age:number, like?:any) { this.name = name; this.age = age; this.like = like; } static run():string { return 'hello'; } }
console.log(Person.race) Person.run()
|
通过static定义的属性、函数只能通过类名去访问
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| class Person { public name:string; private age:number; protected like:any; public static race:string = 'homo'; constructor(name:string, age:number, like?:any) { this.name = name; this.age = age; this.like = like; } static run():string { return this.run0(); } static run0():string { return 'hello'; } }
|
如果两个函数都有static声明,可通过this互相调用
interface定义类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| interface Life { species:string; eat(food:any):any }
interface Intelligence { brain:any; think(something:any):any; }
class Person { public name:string; private age:number; protected like:any; constructor(name:string, age:number, like?:any) { this.name = name; this.age = age; this.like = like; } }
class Student extends Person implements Life, Intelligence { species:string; brain:any; constructor(name:string, age:number, like?:any) { super(name, age, like); this.species = 'homo'; this.brain = 'mind' }
eat(food: any): any { return this.name + 'ate' + food as string; }
think(something: any): any { return this.name + 'got a conclusion: ' + something as string; } }
|
抽象类
在类中可以定义抽象方法,即只定义接口,不实现。
含有抽象方法的类是抽象类,抽象类不能实例化,一般作为父类,由子类继承后去实现抽象方法。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| abstract class Life { protected species:string = ""; protected constructor(species:string) { this.species = species; } abstract eat(food:any):any getSpecies():string { return this.species; } }
class Person extends Life { name:string; constructor(species:string, name:string) { super(species); this.name = name; } eat(food: any): any { return this.name + 'ate' + food as string; } }
|