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

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

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


当前回答

我唯一能告诉你的是getter

Var foo = { 5, b: 6, 获取c() { 返回。A + this.b; } } Console.log (foo.c) // 11

这是由ECMAScript第5版规范引入的一个语法扩展,大多数现代浏览器(包括IE9)都支持该语法。

其他回答

get属性工作得很好,你也可以对只运行一次的“昂贵”函数使用绑定闭包(这只适用于var,而不适用于const或let)

var info = { address: (function() { return databaseLookup(this.id) }).bind(info)(), get fullName() { console.log('computing fullName...') return `${this.first} ${this.last}` }, id: '555-22-9999', first: 'First', last: 'Last', } function databaseLookup() { console.log('fetching address from remote server (runs once)...') return Promise.resolve(`22 Main St, City, Country`) } // test (async () => { console.log(info.fullName) console.log(info.fullName) console.log(await info.address) console.log(await info.address) console.log(await info.address) console.log(await info.address) })()

另一种方法是在给对象赋值之前先声明对象:

const foo = {};
foo.a = 5;
foo.b = 6;
foo.c = foo.a + foo.b;  // Does work
foo.getSum = () => foo.a + foo.b + foo.c;  // foo.getSum() === 22

这样,就可以使用对象变量名访问已经分配的值。 最适合config.js文件。

我唯一能告诉你的是getter

Var foo = { 5, b: 6, 获取c() { 返回。A + this.b; } } Console.log (foo.c) // 11

这是由ECMAScript第5版规范引入的一个语法扩展,大多数现代浏览器(包括IE9)都支持该语法。

我使用下面的代码作为替代,它工作。变量也可以是array。(@福斯托R.)

var foo = {
  a: 5,
  b: 6,
  c: function() {
    return this.a + this.b;
  },

  d: [10,20,30],
  e: function(x) {
    this.d.push(x);
    return this.d;
  }
};
foo.c(); // 11
foo.e(40); // foo.d = [10,20,30,40]

你可以这样做:

var foo = {
   a: 5,
   b: 6,
   init: function() {
       this.c = this.a + this.b;
       return this;
   }
}.init();

这将是对象的某种一次性初始化。

请注意,您实际上是将init()的返回值分配给foo,因此必须返回this。