1

I am struggling to get this to work. I understand that static variables cannot be declared in a class in ES 6 format. How can one declare constants within a class and also access it within the class itself

here is what i have . I am trying to access the constructor value for the constants while $onINit. I do see this.constructor.Consts has the right values . However when i try accessing them using this.getActionConsts.A , It is not there.

Any clues ?

Or is there a better method of defining the constants

class ActionCtrl {

    constructor($scope) {
      this.$scope = $scope;
    }

    static get Consts() {
      return {
        A: '5010',
        B: '5020',
        C: '5030'
      };
    }

    getActionConsts() {
      return this.constructor.Consts;
    }

    $onInit() {
      this.Actions = [{
        'id': this.getActionConsts.A,
        'title': '1'
      }, {
        'id': this.getActionConsts.B,
        'title': '1'
      }];
    }
}
RobG
  • 142,382
  • 31
  • 172
  • 209
looneytunes
  • 741
  • 4
  • 16
  • 35

1 Answers1

2

You aren't calling getActionConts inside of $onInit(). It works when you change this.getActionConsts.A to this.getActionConsts().A. Also you can use the class name instead of this.constructor its a bit cleaner. I used these docs if you want to read more https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static

When I work with constants I just use the const declaration and declare my constants outside of the class. Angular has some fancy ways of defining constants as well which I can't recall of the top of my head.

Daniel Kobe
  • 9,376
  • 15
  • 62
  • 109
  • Thanks @Daniel Kobe . However , when we declare the consts outside the class, is it possible that the constants can interefere with other constants declared outside other classes ? – looneytunes Sep 06 '16 at 01:45
  • If constants interefere it will result in an Error. You shouldn't have more than one class per a file anyways. – Daniel Kobe Sep 06 '16 at 02:01
  • 2
    Consider `ActionCtrl.consts = Object.seal({A: '5010',B: '5020',C: '5030'});` after the class declaration, then the getter is `get Consts() { return ActionCtrl.consts;}`. The constants are public, but can't be modified and are kept from becoming global constants. – RobG Sep 06 '16 at 02:25