1

Fast simply newbie question - it is possible to use object parameter in other object parameter (but it is the same object)?

var obj = {
  a : 'a',
  b : 'b',
  ab : 'Our new parameter: ' + (obj.a + obj.b) + 'is presented!',
  test : obj.ab
}

console.log(obj.ab);

So object is not ready when I call obj.ab - any idea how handle this? obj is global object now and rest of the code are using heavy of obj.ab - I don;t want to make significant changes, any simple idea?

Proo1931
  • 103
  • 1
  • 12

1 Answers1

1

You may want to simple convert to a function ab and access the object properties through this.

var obj = {
  a : 'a',
  b : 'b',
  ab : () => 'Our new parameter: ' + (this.obj.a + this.obj.b) + 'is presented!',
  test : () => this.obj.ab
};

console.log(obj.ab());
console.log(obj.test());

// ab: () => is an arrow function
// test: () => is also an arrow function
ricardoorellana
  • 2,270
  • 21
  • 35
  • 1
    thanks I did something similar at the end: var foo = { a: 'a', b: 'b', c: function(){return foo.a + foo.b;}(), d: function(){return foo.c;}() } console.log(foo.c); // ab console.log(foo.d); // ab console.log(foo); // our foo object show proper values – Proo1931 Nov 13 '19 at 04:09
  • Awesome, that way is also correct! – ricardoorellana Nov 13 '19 at 04:53
  • not really... it does not work when I export my globals object and I dunno why. No matter if I use object or this it simply do not work - gives undefined. EDIT: it worked when I execute the function (method) in file that require the globals. So methods in globals object must NOT be invoked. – Proo1931 Nov 13 '19 at 05:07
  • 1
    I see, I recommend you take a look to Module Pattern https://addyosmani.com/resources/essentialjsdesignpatterns/book/#modulepatternjavascript to avoid those problems – ricardoorellana Nov 13 '19 at 05:27
  • Bahhh I think this case is even more specific.... I have globals object inside route (express routes), and at the end it turn out I need instances of my globals object - otherwise app do not work properly. So any idea how to have instance of globals object - accessible through all modules that require it (connected to specific user request - so every user have... someking of own globals object)? Thanks for the link anyway! – Proo1931 Nov 13 '19 at 19:41