Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 633
kpozin Avatar asked Jan 06 '11 14:01

kpozin


People also ask

How is an object property referenced?

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.

What is the correct syntax for declaring an object literal?

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.

What are object literals in JavaScript?

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.

How do you initialize an object in JavaScript?

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 ( {} ).


2 Answers

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.

like image 31
Felix Kling Avatar answered Oct 01 '22 14:10

Felix Kling


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).

like image 114
Christian C. Salvadó Avatar answered Oct 01 '22 15:10

Christian C. Salvadó