首先,简单介绍ES6的class类
class Foo {
constructor(name,age){ // 实例前的构造函数,实例添加name/age属性
this.name = name
this.age = age
}
getName () { // 原型添加getName()方法
return `My name is ${this.name} age : ${this.age}`
}
}
let foo = new Foo('小明',12) // Foo {name:'小名',age:12,__proto__:getName(){}}
ts定义类:
class Foo {
public name:string // 需要提前声明值,默认为public
public age:number
public constructor(_name:string,_age:number){
this.name = _name
this.age = _age
}
public getName ():string { // 原型方法,指定返回值为string类型
return `My name is ${this.name} age : ${this.age}`
}
}
let foo = new Foo('小明',12) // Foo {name:'小名',age:12,__proto__:getName(){}}
这里指定name和age的类型,附部分类型:
attr : sting // sting类型
attr : number // number类型
attr : boolean // boolean类型
attr : string[] // 数组的每一项必须是string类型
attr : number[] // 数组每一项必须是number类型
attr : Array< any>// 数组每一项可以为任意类型
attr : [string,number] // 数组每一项必须是指定类型
attr ?: string // 非必传
提前声明值可以利用参数属性
class Foo {
public constructor(public name:string,public age:number){}
public getName ():void {
console.log(this.name,this.age)
}
}
let foo = new Foo(‘小明’,12) // Foo {name:'小明',age:12,__proto__:getName(){}}
介绍public、private、protected、readonly、static 等标识
class Foo {
pulbic name:string
public constructor (_name?:string) {
this.name = _name || ''
}
}
let foo = new Foo('小明') // Foo {name:'小名'}
class Foo {
private name:string
constructor (_name:string) {
this.name = _name
}
}
let foo = new Foo('小明') // Foo {name:'小名'}
console.log(foo.name) //error: Property 'name' is private;
class Foo {
protected name:string
protected constructor(_name:string){
this.name = _name
}
}
let foo = new Foo('小明') //error: Constructor of class 'Foo' is protected
class Foo {
readonly name:string
public constructor(_name:string){
this.name = _name
}
}
let foo = new Foo('小明') // Foo {name:'小明'}
foo.name = '小红' //error: Cannot assign to 'name' because it is a constant or a read-only property.
class Foo {
static age:number = 12
public constructor(private name:string){}
pubilc getAge ():void {
console.log(Foo.age)
}
}
let foo = new Foo('小明') // Foo {name:'小明',__proto__:getAge(){}}
console.log(foo.getAge()) // 12
ts继承:
class Foo {
public name:string
public age:number
public construcor (_name:string,_age:number) {
this.name = _name
this.age = _age
}
getName ():string {
return this.name
}
}
class Bar extends Foo {
private className:string
public constructor (_name:string,_age:number,_className:string) {
super(_name,_age)
this.calssName = _className
}
public getClassName ():void {
console.log(this.className)
}
}
let bar = new Bar('小明',12,'一年级') // Bar {name:'小明',age:12,className:'一年级'}
console.log(bar.getName()) // 小明
console.log(bar.getClassName()) // 一年级