typescript class

Like Java language, typescript's class must have a constructer for the local variables.

The variable types are: public, protected, private, static, and hiden. The public, protected, private have different inheritance implications, and can be access through this.xxx. The static is just static, can be accessed through Class.static_var. Hiden variable is with a hash prefix #hidden_var, it can not be seen by child class.

class Person{

  public id: number;

  protected gender: string;

  private name: string;

  static flag = 'good'

  #hiden_var = 'cant see'


  constructor(name: string, id: number, gender: string){

    this.name = name;

    this.id = id;

    this.gender = gender;

  }

  say_hi = () => console.log('hi' + Person.flag + this.#hiden_var);

}

let p = new Person('kiwi',1,'m')

p.say_hi()


Getter and setter

For private variables, it can not be seen directly by external, so a get and a set methods are needed. 

The handy part is, once defined, it doesn't need to call a method, but just assign value directly to the funciton name!

class Person2{

  private _name: string;  

  constructor(name: string){

    this._name = name;

  }

  public set name(name:string){

    this._name = name;

  }

  public get name(){

    return this._name;

  }

}

let p2 = new Person2('kiwi')

p2.name = 'mate'  //the name is the kind of the function name, but can be assigned directly

console.log(p2.name)


Inheritance

Child extends Parent. Like java again, the constructure method needs to call parents constructure through super()

class Person3 extends Person2{

  constructor(name: string){

    super(name)

  }

  hello = () => {console.log('hellow' + this.name)}

}

let p3 = new Person3('kiwi')

console.log(p3.name)