6

I have been doing Node.js and front-end Javascript long enough so that I should know the answer to this.

Say I have an object literal like this:

       'lectal_api_server': {
            host: 'https://xyz.herokuapp.com',
            port:  process.env.PORT || 80,
            url:  'https://xyz.herokuapp.com:80'
        }

is it possible to do something like this:

      'lectal_api_server': {
            host: 'https://xyz.herokuapp.com',
            port:  process.env.PORT || 80,
            url:   this.host + ':' + this.port
         }

I don't believe something like this is possible with ES5 but is it possible with ES6?

Alexander Mills
  • 90,741
  • 139
  • 482
  • 817
  • Properties _host & port_ has already defined in __location__ object. So What the point of this question? –  Nov 21 '15 at 22:53
  • 1
    @nAz - this is a node.js question, not a browser question (see the tags on the question). There is no **location** object in node.js. – jfriend00 Nov 21 '15 at 22:57
  • @jfriend00 oh, thought that a question belongs to front-end. Thanks –  Nov 21 '15 at 22:59

2 Answers2

13

You can use a method or a getter function. Both will work but the getter function will make the property behave as a property and not a method, which can be useful in certain cases.

// As a method

lectal_api_server = {
  host: 'https://lectal-api.herokuapp.com',
  port: 80,
  getUrl: function() {
    return this.host + ':' + this.port
  }
}

console.log('%c As a method', 'font-weight: bold');

console.log(lectal_api_server.getUrl());

for (var key in lectal_api_server) {
  console.log(key, ':', lectal_api_server[key]);
}

console.log(JSON.stringify(lectal_api_server));

// Using a getter

lectal_api_server = {
  host: 'https://lectal-api.herokuapp.com',
  port: 80,
  get url() {
    return this.host + ':' + this.port
  }
}

console.log('%c Using a getter', 'font-weight: bold');

console.log(lectal_api_server.url);

for (var key in lectal_api_server) {
  console.log(key, ':', lectal_api_server[key]);
}

console.log(JSON.stringify(lectal_api_server));

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get

Julien Grégoire
  • 16,864
  • 4
  • 32
  • 57
3

Not exactly like your approach, but you could use a function as a constructor to create an object with this behaviour:

var LectalApiServer = function( host, port ){
    this.host = host;
    this.port = port;
    this.url = this.host + ":" + this.port;
};

var myLectalApiServer = new LectalApiServer( "http://...", 80);
console.log(myLectalApiServer.url);
malifa
  • 8,025
  • 2
  • 42
  • 57