-1

I'm trying to figure out how I can organize my variables, and this is the outcome I want:

settings.txt.token => 'txt'
settings.txt.path => '/txt/'

This is obviously a very simple example, but I want settings.txt.path to depend on settings.txt.token. So a sudo decleration would be:

export var txt = {
   token: 'txt',
   path: '/' + token + '/'
};

Is there a good way to do this? Note that I'm using ES6.

2 Answers2

1

A static declaration of one property cannot refer directly to another property in the same object because the object itself is in the process of formation and does not fully exist yet and javascript does not have syntax for referencing sibling properties from a static declaration. So, you have to postpone the calculation of the value for the new property until after the object exists. You can do that a couple of ways.

One is with a getter:

export var txt = {
   token: 'txt',
   get path() { return '/' + this.token + '/';}
};

The other is to just add the property to the object after the static declaration has completed:

export var txt = {
   token: 'txt',
};
txt.path = '/' + txt.token + '/';

The getter option has the advantage that if .token is modified, subsequent requests for .path will automatically reflect the new value of .token. The second option is not dynamically linked. The txt.path value will not automatically change if txt.token is changed. You can select either behavior.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
0

Yeah, you can't reference fields in object initializer. But you can in constructor:

export var txt = new function(){
    this.token = "txt";
    this.path = "/" + this.token + "/";
}
weaknespase
  • 1,014
  • 8
  • 15