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

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

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


当前回答

下面是对象中'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
    })()
  },
}

其他回答

如果你想使用原生JS,其他答案提供了很好的解决方案。

但是如果你愿意写自引用对象,比如:

{ 
  a: ...,
  b: "${this.a + this.a}",
}

我写了一个叫做self- references -object的npm库,它支持这种语法并返回一个原生对象。

这里有一个简洁的ES6方法:

Var foo = (o => ({ ……啊, C: o.a + o.b ({})) 5, b: 6 }); console.log (foo);

我用它来做这样的事情:

const常量= Object.freeze( (_ => ({ _, flag_data: { (_。a_flag]:“foo”, (_。b_flag]:“酒吧”, [_.c_flag]:“力量” } ({})) a_flag: 5 b_flag: 6, c_flag: 7, }) ); console.log (constants.flag_data [constants.b_flag]);

这里发布的其他答案更好,但这里有一个替代答案:

在初始化时设置值(不是getter或派生的,等等) 不需要任何类型的init()或对象字面量之外的代码 是一个对象文字,而不是一个工厂函数或其他对象创建机制。 不应该有任何性能影响(初始化时除外)

自动执行匿名函数和窗口存储

var foo = {
    bar:(function(){
        window.temp = "qwert";
        return window.temp;
    })(),
    baz: window.temp
};

订单是有保证的(bar before baz)

它当然会污染window,但我无法想象有人会编写一个需要window的脚本。Temp是持久的。如果你偏执的话,可以试试tempMyApp。

它也很丑,但偶尔有用。一个例子是,当你使用一个具有严格初始化条件的API时,你不想重构,所以范围是正确的。

当然,它是干的。

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

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: (window.secreta = 5),
    b: (window.secretb = 6),
    c: window.secreta + window.secretb
};

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