有什么方法可以让下面的东西在JavaScript中工作?
var foo = {
a: 5,
b: 6,
c: this.a + this.b // Doesn't work
};
在当前的表单中,这段代码显然抛出了一个引用错误,因为它没有引用foo。但是有没有办法让对象字面量的属性值依赖于之前声明的其他属性呢?
有什么方法可以让下面的东西在JavaScript中工作?
var foo = {
a: 5,
b: 6,
c: this.a + this.b // Doesn't work
};
在当前的表单中,这段代码显然抛出了一个引用错误,因为它没有引用foo。但是有没有办法让对象字面量的属性值依赖于之前声明的其他属性呢?
当前回答
两种惰性解决方案
这里已经有了很好的答案,我不是这方面的专家,但我是懒惰方面的专家,以我的专家眼光来看,这些答案似乎不够懒惰。
第一个:从匿名函数返回对象
T.J. Crowder, Henry Wrightson和Rafael Rocha的回答略有不同:
Var foo = (() => { //粘贴原始对象 Const foo = { 5, b: 6, }; //使用它们的属性 foo.c = foo。A + foo.b; //做任何你想做的事情 //最后返回对象 返回foo; }) (); console.log (foo);
稍微有点好处的是,只需要原样粘贴您的原始对象,而不用担心参数等(恕我直言,包装器函数通过这种方式变得相当透明)。
第二:使用setTimeout
如果你不需要立即使用foo.c,这个方法可以工作:
Var foo = { 5, b: 6, c: setTimeout(() => foo.c = foo.c。A + foo。b, 0) }; //首先,foo.c将是setTimeout返回的整数 console.log (foo); //但如果这不是一个问题,当时间进入事件循环时,值将被更新 setTimeout(() => console.log(foo), 0);
其他回答
在对象字面量上创建新函数并调用构造函数似乎与原始问题完全不同,而且没有必要。
在对象文字初始化期间不能引用兄弟属性。
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的答案几乎相同,但没有使用函数。
你可以这样做:
var foo = {
a: 5,
b: 6,
init: function() {
this.c = this.a + this.b;
return this;
}
}.init();
这将是对象的某种一次性初始化。
请注意,您实际上是将init()的返回值分配给foo,因此必须返回this。
只是为了思考-地点对象的属性的时间轴:
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);