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

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

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


当前回答

你可以这样做:

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

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

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

其他回答

某种终结应该能解决这个问题;

var foo = function() {
    var a = 5;
    var b = 6;
    var c = a + b;

    return {
        a: a,
        b: b,
        c: c
    }
}();

在foo中声明的所有变量对foo来说都是私有的,就像你在任何函数声明中所期望的那样,因为它们都在作用域中,所以它们都可以相互访问,而不需要引用this,就像你在函数中所期望的那样。不同之处在于这个函数返回一个对象,该对象公开私有变量并将该对象赋值给foo。最后,使用return{}语句返回希望作为对象公开的接口。

然后,函数在结束时使用()执行,这将导致整个foo对象被求值,其中的所有变量被实例化,返回对象被作为foo()的属性添加。

只是为了大家的娱乐:

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

您可以使用模块模式来实现这一点。就像:

var foo = function() {
  var that = {};

  that.a = 7;
  that.b = 6;

  that.c = function() {
    return that.a + that.b;
  }

  return that;
};
var fooObject = foo();
fooObject.c(); //13

使用这个模式,你可以根据需要实例化几个foo对象。

http://jsfiddle.net/jPNxY/1/

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

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文件。

只是为了思考-地点对象的属性的时间轴:

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

console.log(foo.c())

上面也有更好的答案。这是我如何修改你质疑的示例代码。

更新:

var foo = {
    get a(){return 5},
    get b(){return 6},
    get c(){return this.a + this.b}
}
// console.log(foo.c);