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?
Objects are assigned and copied by reference. In other words, a variable stores not the “object value”, but a “reference” (address in memory) for the value. So copying such a variable or passing it as a function argument copies that reference, not the object itself.
Declaring methods and properties using Object Literal syntax The Object literal notation is basically an array of key:value pairs, with a colon separating the keys and values, and a comma after every key:value pair, except for the last, just like a regular array.
Object Literal. In plain English, an object literal is a comma-separated list of name-value pairs inside of curly braces. Those values can be properties and functions.
Objects can be initialized using new Object() , Object. create() , or using the literal notation (initializer notation). An object initializer is a comma-delimited list of zero or more pairs of property names and associated values of an object, enclosed in curly braces ( {} ).
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
.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With