有什么方法可以让下面的东西在JavaScript中工作?

var foo = {
    a: 5,
    b: 6,
    c: this.a + this.b  // Doesn't work
};

在当前的表单中,这段代码显然抛出了一个引用错误,因为它没有引用foo。但是有没有办法让对象字面量的属性值依赖于之前声明的其他属性呢?


当前回答

加上一个选项,因为我没有看到这种情况。如果您不希望在a或b更新时更新c,那么ES6 IIFE可以很好地工作。

var foo = ((a,b) => ({
    a,
    b,
    c: a + b
}))(a,b);

对于我的需要,我有一个对象,涉及到一个数组,最终将在循环中使用,所以我只想计算一些常见的设置一次,所以这是我有:

let processingState = ((indexOfSelectedTier) => ({
    selectedTier,
    indexOfSelectedTier,
    hasUpperTierSelection: tiers.slice(0,indexOfSelectedTier)
                         .some(t => pendingSelectedFiltersState[t.name]),
}))(tiers.indexOf(selectedTier));

因为我需要为indexOfSelectedTier设置一个属性,我需要在设置hasUpperTierSelection属性时使用该值,我首先计算该值,并将其作为参数传递给IIFE

其他回答

只是为了大家的娱乐:

var foo = (This={ 5, b: 6,})=>({… c:。a +这个。b }))( ); console.log (foo);

有几种方法可以做到这一点;这是我要用的:

function Obj() {
 this.a = 5;
 this.b = this.a + 1;
 // return this; // commented out because this happens automatically
}

var o = new Obj();
o.b; // === 6

在对象字面量上创建新函数并调用构造函数似乎与原始问题完全不同,而且没有必要。

在对象文字初始化期间不能引用兄弟属性。

var x = { a: 1, b: 2, c: a + b } // not defined 
var y = { a: 1, b: 2, c: y.a + y.b } // not defined 

计算属性的最简单的解决方案如下(没有堆,没有函数,没有构造函数):

var x = { a: 1, b: 2 };

x.c = x.a + x.b; // apply computed property

下面是对象中'this'行为的一个例子。

this.prop = 'external';
global.prop = 'global.prop';
const that = this;

const a = {
  prop: 'internal',
  prop1: this.prop, //external

  log() {
    return this.prop //internal
  },
  log1: () => {
    return this.prop //external
  },
  log2: () => {
    return function () {
      return this.prop; //'global.prop' in node; 'external' in chrome
    }()
  },
  log3: function () {
    return (() => {
      return this.prop; //internal
    })()
  },
}
var x = {
    a: (window.secreta = 5),
    b: (window.secretb = 6),
    c: window.secreta + window.secretb
};

这与@slicedtoad的答案几乎相同,但没有使用函数。