2021年6月7日 星期一

[typescript, class, constructor] How to create and assign a class instance property from a constructor parameter

How to create and assign a class instance property from a constructor parameter


Method
1: Short-Cut Syntax
You see this style spread in whole ionic project typescript files.

class MyClass{

    constructor(public myPublicVar:MyType, normalArg){

    }


    myMethod(){

           this.myPublicVar = ...;

           this.normalArg = ...;   // Error: there is no normalArg property 

    }

}


Method 2: Traditional
Syntax

class MyClass{

    public myPublicVar:MyType = new MyType();

    constructor(normalArg){

          this.normalArg = ...;   // Error: there is no normalArg property

    }


    myMethod(){

           this.myPublicVar = ...;

    }

}




Enjoy!
by Jing.

Reference