Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of 'this' inside object literal in ES6 [duplicate]

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?

like image 636
Alexander Mills Avatar asked Nov 21 '15 22:11

Alexander Mills


2 Answers

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

like image 144
Julien Grégoire Avatar answered Oct 05 '22 22:10

Julien Grégoire


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);
like image 35
malifa Avatar answered Oct 05 '22 23:10

malifa