有什么方法可以让下面的东西在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。但是有没有办法让对象字面量的属性值依赖于之前声明的其他属性呢?
当前回答
如果你想使用原生JS,其他答案提供了很好的解决方案。
但是如果你愿意写自引用对象,比如:
{
a: ...,
b: "${this.a + this.a}",
}
我写了一个叫做self- references -object的npm库,它支持这种语法并返回一个原生对象。
其他回答
下面是对象中'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 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);
显而易见,简单的答案是缺失的,所以为了完整:
但是有没有办法让对象字面量的属性值依赖于之前声明的其他属性呢?
不。这里的所有解决方案都将它延迟到对象创建之后(以各种方式),然后分配第三个属性。最简单的方法就是这样做:
var foo = {
a: 5,
b: 6
};
foo.c = foo.a + foo.b;
其他的都是做同样事情的更间接的方式。(Felix的方法特别聪明,但需要创建和销毁临时函数,这增加了复杂性;并且要么在对象上留下额外的属性,要么[如果删除该属性]影响该对象上后续属性访问的性能。)
如果你需要它都在一个表达式中,你可以不使用temporary属性:
var foo = function(o) {
o.c = o.a + o.b;
return o;
}({a: 5, b: 6});
当然,如果你需要多次这样做:
function buildFoo(a, b) {
var o = {a: a, b: b};
o.c = o.a + o.b;
return o;
}
然后你需要使用它的地方:
var foo = buildFoo(5, 6);
两种惰性解决方案
这里已经有了很好的答案,我不是这方面的专家,但我是懒惰方面的专家,以我的专家眼光来看,这些答案似乎不够懒惰。
第一个:从匿名函数返回对象
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);
有几种方法可以做到这一点;这是我要用的:
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