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?
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
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With