【问题标题】:ES6 call with variable inside array that is inside an object with multiple objects or propertiesES6 使用数组内的变量调用,该数组位于具有多个对象或属性的对象内
【发布时间】:2016-11-18 06:17:16
【问题描述】:

花了我很多时间来构图标题,唉,还是很难理解。

反正这是我想做的,但不知道怎么做,或者是否可能,所以请赐教。

这里是:

const defaults = {
  backgroundcolor: '#000',
  color: '#fff',
  getProps: [
    'some value',
    `${this.backgroundcolor}`,
    `${this.color}`
  ]
};

我知道我可以像defaults.backgroundcolor 这样在对象之外调用它,但我想知道上面的代码是否也可以实现?提前致谢。

【问题讨论】:

  • this 在静态声明中没有您希望它具有的值。 Javascript 不能那样工作。您可以在声明对象后分配defaults.getProps,然后您可以引用对象中的其他属性。

标签: arrays ecmascript-6 javascript-objects


【解决方案1】:

如果您将getProps 设为方法,则可以使其工作:

const defaults = {
 backgroundcolor: '#000',
 color: '#fff',
 getProps: function () { return [
   'some value',
   `${this.backgroundcolor}`,
   `${this.color}`
 ];}
};

var x = defaults.getProps();

console.log(x);

如果它必须是一个可以在没有函数括号的情况下访问的属性,那么使用defineProperty

const defaults = Object.defineProperty({
        backgroundcolor: '#000',
        color: '#fff',
    }, 'getProps', {
        get: function () { return [
           'some value',
           `${this.backgroundcolor}`,
           `${this.color}`
        ];}
});

var x = defaults.getProps;

console.log(x);

您也可以创建一个立即执行的构造函数:

const defaults = new (function() {
    this.backgroundcolor = '#000';
    this.color = '#fff';
    this.getProps = [
       'some value',
       `${this.backgroundcolor}`,
       `${this.color}`
    ];
})();

var x = defaults.getProps;

console.log(x);

【讨论】:

  • 非常感谢。奇迹般有效。我可以使用 () => 对匿名函数做同样的事情吗?我试过了,没明白。
  • 不,=> 语法 does not set this 关键字。
猜你喜欢
  • 1970-01-01
  • 2020-08-15
  • 1970-01-01
  • 2022-12-17
  • 2015-04-24
  • 1970-01-01
  • 1970-01-01
  • 2022-11-21
  • 2019-07-31
相关资源
最近更新 更多