javascript - Self-references in object literal declarations -
is there way following work in javascript?
var foo = { a: 5, b: 6, c: this.a + this.b // doesn't work };
in current form, code throws reference error since this
doesn't refer foo
. is there way have values in object literal's properties depend on other properties declared earlier?
you like:
var foo = { a: 5, b: 6, init: function() { this.c = this.a + this.b; return this; } }.init();
this kind of 1 time initialization of object.
note assigning return value of init()
foo
, therefore have return this
.
Comments
Post a Comment