references in object literal declarations
Is there any way to get something like the following to work in JavaScript?
var foo = {
a: 5,
b: 6,
c: this.a + this.b // Doesn't work
};
In the current form, this code obviously throws a reference error since this
doesn't refer to foo
. But is there any way to have values in an object literal's properties depend on other properties declared earlier?
Well, the only thing that I can tell you about are getters:
var foo = {
a: 5,
b: 6,
get c () {
return this.a + this.b;
}
};
foo.c; // 11
This is a syntactic extension introduced by the ECMAScript 5th Edition Specification, the syntax is supported by most modern browsers (including IE9).
You could do something like:
var foo = {
a: 5,
b: 6,
init: function() {
this.c = this.a + this.b;
return this;
}
}.init();
This would be some kind of one time initialization of the object.
Note that you are actually assigning the return value of init()
to foo
, therefore you have to return this
.
The obvious, simple answer is missing, so for completeness:
But is there any way to have values in an object literal's properties depend on other properties declared earlier?
No. All of the solutions here defer it until after the object is created (in various ways) and then assign the third property. The simplest way is to just do this:
var foo = {
a: 5,
b: 6
};
foo.c = foo.a + foo.b;
All others are just more indirect ways to do the same thing. (Felix's is particularly clever, but requires creating and destroying a temporary function, adding complexity; and either leaves an extra property on the object or [if you delete
that property] impacts the performance of subsequent property accesses on that object.)
If you need it to all be within one expression, you can do that without the temporary property:
var foo = function(o) {
o.c = o.a + o.b;
return o;
}({a: 5, b: 6});
Or of course, if you need to do this more than once:
function buildFoo(a, b) {
var o = {a: a, b: b};
o.c = o.a + o.b;
return o;
}
then where you need to use it:
var foo = buildFoo(5, 6);
链接地址: http://www.djcxy.com/p/94920.html
上一篇: 对象的方法被调用时没有绑定?
下一篇: 对象字面声明中的引用