Self-references in object literals / initializers
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 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).
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);
Simply instantiate an anonymous function:
var foo = new function () { this.a = 5; this.b = 6; this.c = this.a + this.b; };
Now in ES6 you can create lazy cached properties. On first use the property evaluates once to become a normal static property. Result: The second time the math function overhead is skipped.
The magic is in the getter.
const foo = { a: 5, b: 6, get c() { delete this.c; return this.c = this.a + this.b } };
In the arrow getter this
picks up the surrounding lexical scope.
foo // {a: 5, b: 6} foo.c // 11 foo // {a: 5, b: 6 , c: 11}
Some closure should deal with this;
var foo = function() { var a = 5; var b = 6; var c = a + b; return { a: a, b: b, c: c } }();
All the variables declared within foo
are private to foo
, as you would expect with any function declaration and because they are all in scope, they all have access to each other without needing to refer to this
, just as you would expect with a function. The difference is that this function returns an object that exposes the private variables and assigns that object to foo
. In the end, you return just the interface you want to expose as an object with the return {}
statement.
The function is then executed at the end with the ()
which causes the entire foo object to be evaluated, all the variables within instantiated and the return object added as properties of foo()
.
You could do it like this
var a, b var foo = { a: a = 5, b: b = 6, c: a + b }
That method has proven useful to me when I had to refer to the object that a function was originally declared on. The following is a minimal example of how I used it:
function createMyObject() { var count = 0, self return { a: self = { log: function() { console.log(count++) return self } } } }
By defining self as the object that contains the print function you allow the function to refer to that object. This means you will not have to ‘bind’ the print function to an object if you need to pass it somewhere else.
If you would, instead, use this
as illustrated below
function createMyObject() { var count = 0 return { a: { log: function() { console.log(count++) return this } } } }
Then the following code will log 0, 1, 2 and then give an error
var o = createMyObject() var log = o.a.log o.a.log().log() // this refers to the o.a object so the chaining works log().log() // this refers to the window object so the chaining fails!
By using the self method you guarantee that print will always return the same object regardless of the context in which the function is ran. The code above will run just fine and log 0, 1, 2 and 3 when using the self version of createMyObject()
.
For completion, in ES6 we’ve got classes (supported at the time of writing this only by latest browsers, but available in Babel, TypeScript and other transpilers)
class Foo { constructor(){ this.a = 5; this.b = 6; this.c = this.a + this.b; } } const foo = new Foo();
You can do it using the module pattern. Just like:
var foo = function() { var that = {}; that.a = 7; that.b = 6; that.c = function() { return that.a + that.b; } return that; }; var fooObject = foo(); fooObject.c(); //13
With this pattern you can instantiate several foo objects according to your need.
There are several ways to accomplish this; this is what I would use:
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