HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptCritical

Self-references in object literals / initializers

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
objectselfinitializersliteralsreferences

Problem

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?

Solution

Well, the only thing that I can tell you about are getter:



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

console.log(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).

Context

Stack Overflow Q#4616202, score: 1043

Revisions (0)

No revisions yet.