Lanti Lanti - 2 months ago 7
Javascript Question

Reference object inside same variable

I have this javascript file which is containing styles in an object for a React app:

const styles = {
fonts: {
Georgia: 'Georgia, \'Times New Roman\', Times, serif',
},
App: {
textAlign: 'center',
fontFamily: this.fonts.Georgia,
},
};

module.exports = styles;


fontFamily: this.fonts.Georgia
would reference
App: { fonts: '' }
object, but what I want to do is to access the already defined
fonts
object inside
styles
. How can I do that?

What works is:

const fonts = {
Georgia: 'Georgia, \'Times New Roman\', Times, serif',
};

const styles = {
App: {
textAlign: 'center',
fontFamily: fonts.Georgia,
},
};

module.exports = styles;


This is works in this case, but the upper solution would be much nicer.

Answer

Simply speaking, you can't. JavaScript objects have no notion of parentage.

const App = {
  textAlign: 'center',
  fontFamily: this.fonts.Georgia, // ???
}

What does this means in that context?

Moreover

const styles = {
  fonts: 'Georgia, \'Times New Roman\', Times, serif',
  App
};

This is the same object as the first one you've posted.

Your only choice is to split the two objects as you have. To hide this detail away from outside of the module, you can do the following:

module.exports = {fonts, styles};

That will make it so that both the fonts and the styles are available to the outside. You can mix and match to get the exact object you want, but the actual structure is irrelevant for the question.

Comments