简体   繁体   English

同一变量内的引用对象

[英]Reference object inside same variable

I have this javascript file which is containing styles in an object for a React app: 我有这个javascript文件,它在React应用程序的对象中包含样式:

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 . fontFamily: this.fonts.Georgia将引用App: { fonts: '' }对象,但是我要做的是访问styles已经定义的fonts对象。 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. 在这种情况下这是可行的,但是更高的解决方案会更好。

Simply speaking, you can't. 简而言之,你做不到。 JavaScript objects have no notion of parentage. JavaScript对象没有亲子关系的概念。

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

What does this means in that context? 在这种情况下this意味着什么?

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. 您可以混合匹配以获取所需的确切对象,但是实际结构与该问题无关。

An approach that works is using a getter to retrieve the fonts property dynamically. 一种可行的方法是使用吸气剂动态检索fonts属性。

 const styles = { fonts: { Georgia: 'Georgia, \\'Times New Roman\\', Times, serif', }, App: { textAlign: 'center', get fontFamily () { return styles.fonts.Georgia }, }, }; console.log(styles); 

Note that this has some drawbacks: 请注意,这有一些缺点:

  • The App.fontFamily property will always mirror fonts if it changes dynamically. 如果App.fontFamily属性动态更改,它将始终镜像fonts This may or may not be the desired behavior. 这可能是也可能不是所需的行为。
  • Without a setter, App.fontFamily can only be get, not set. 如果没有设置器,则只能获取App.fontFamily ,不能设置它。
  • Some serializers may not process objects with non-value properties as one would expect. 一些序列化程序可能不会像预期的那样处理具有非值属性的对象。 I guess this is true for some other libraries, too. 我想其他一些库也是如此。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM