Typescript中的静态属性和静态方法
在ts中使用静态属性和方法,需要有static关键字,且在静态方法里只能用静态属性
举两个栗子
在es5中
function Person(){
this.run1 = function (){} // 实例方法,实例化后调用
}
var p = new Person() // 实例化
p.run1() //调用实例方法
Person.run2 = function (){} // 静态方法,类名直接调用
Person.name = '哈哈哈' // 静态属性
Person.run2() // 静态方法的调用,类名直接调用
在ts中
class Person{
public name:string;
static sex = '男' //静态属性
constructor(name:string){
this.name=name;
}
run(){ //实例方法
console.log(`${this.name}在运动`)
}
work(){
console.log(`${this.name}在工作`)
}
static print(){ //静态方法
console.log('静态方法') //注意这里无法直接调用类中属性,如this.name不可调用,但是可以调用静态属性Person.sex
}
}
var d = new Person('小摆')
d.run() //实例方法调用
Person.print() //静态方法调用 使用静态属性、静态方法前要加类名