WITO WITO - 8 months ago 103
Javascript Question

how to declare object with recursive properties? in nodejs

I am declaring:

var ENV = {
VERSION: 1,
SERVER: 'midomain.com',
SERVER_DEV: 'testdomain.dev',
API_ROUTE: 'socket/',
API: (false) ? this.SERVER + '/' + this.API_ROUTE : this.SERVER_DEV + '/' + this.API_ROUTE };


should get:

{ VERSION: 1,SERVER: 'midomain.com',SERVER_DEV: 'testdomain.dev',API_ROUTE: 'socket/', API: 'testdomain.dev/socket/' }


but I get

{ VERSION: 1,SERVER: 'midomain.com',SERVER_DEV: 'testdomain.dev',API_ROUTE: 'socket/', API: 'undefined/undefined' }

Answer Source

Because in that case context is global, not an your object. You can check it with an example:

window.b = 666;

let a = {
 prop: this.b
}

console.log(a); // display: {prop: 666}

You can fill your object properties one-by-one

let ENV       = {};
ENV.VERSION = 1;
ENV.SERVER = 'midomain.com';
ENV.API = ENV.SERVER;

or create function with 'new' syntax

var ENV = new function() {
   this.VERSION = 1;
   this.SERVER = 'midomain.com';
   this.API = this.SERVER;
};
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download