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

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

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


当前回答

我使用下面的代码作为替代,它工作。变量也可以是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 = 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()的属性添加。

这里有一个简洁的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]);

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

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/

如果你的对象被编写成一个返回对象的函数,并且你使用ES6对象属性“方法”,那么它是可能的:

const module = (state) => ({
  a: 1,
  oneThing() {
    state.b = state.b + this.a
  },
  anotherThing() {
    this.oneThing();
    state.c = state.b + this.a
  },
});

const store = {b: 10};
const root = module(store);

root.oneThing();
console.log(store);

root.anotherThing();
console.log(store);

console.log(root, Object.keys(root), root.prototype);

可维护性很好的替代语法:

let a = 5;
let b = 6;
let foo = {
  a,
  b,
  c: a+b,
};

这是因为如果您没有显式地指定名称,JavaScript将使用变量名作为新创建的对象的属性名。对于像这样的短数组,如果在函数中,我个人会使用单行语法和return:

let a = 5;
let b = 6;
return { a, b, c:a+b };