Skip to content

静态方法getter,setter和Static

static

class Per{
    public name:string;
    static age:number=23;
    constructor(name:string){
        this.name=name
    }
    run(){
      console.log('run  '+this.name)
    }
    word(){
        console.log('word   '+this.name)
    }
    static print(){ //静态方法
        console.log('print '+this.age)
    }
}
var fun=new Per('haobc');
Per.print();
fun.run();
fun.word();

get 和set

class Person {
  constructor( private _name: string) { //因为此时是private,只在类的内部可以使用
    this._name = _name;
  }
  //是一个属性
  get name() {  //通过get属性 可以将age,在类的外面使用
    return this._name+"c" //在get属性中我们可以做一些处理
  }
  set name( name: string ) {
    this._name=name //在set属性中我们也可以做一些处理
  }
}

let person = new Person('haob');
console.log(person.name) //打印的就是haobc
person.name='zrf' //设置name的值
console.log(person.name) //打印的就是zrfc