Self-references in object literal declarations

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?

Access JavaScript Object Literal value in same object [duplicate]

Possible Duplicate: Self-references in object literal declarations Is there any way access the value of a property name in the same object literal? Something like this: myFunction.init({ varOne: ‘so

Can I alias a key in an object literal? [duplicate]

Possible Duplicate: Self-references in object literal declarations I have an object literal which is used as a configuration element and is looked up for keys. customRendering:{ key1: func(){….},

Make Closure Compiler merge several object property declarations as one big literal

I split my code into several files, and then run a script to merge and compile them (with ADVANCED_OPTIMIZATIONS). A big part of the functionality is implemented in a single object’s prototype. So whe

Can’t define variable in JavaScript object literal [duplicate]

This question already has an answer here: Self-references in object literal declarations 10 answers Why does this code work… var message = { texts: { text1: ‘Hello’, text2: ‘World’ }, greet:

Dynamic object literal in javascript?

Is it possible to creat an object literal on the fly? Like this: var arr = [ ‘one’, ‘two’, ‘three’ ]; var literal = {}; for(var i=0;i<arr.length;i++) { // some literal push method here! /* literal

Javascript object literal inside object literal [closed]

In the following JavaScript example, are we seeing 2 object literals as properties of an object literal? dw_Tooltip.content_vars = { link1: { img: ‘images/dw-btn.gif’, txt: ‘dyn-web button’, w: 100 },

Javascript Object literal

Here is my object literal: var obj = {key1: value1}; How can I add: {key1: value1,value2,value3} to the object?

Object literal and static variable

Object literal are considered as static object. So, object literal should contains only static variable but in the following piece of code var obj = { a : hello, foo : function(){ console.log(this.a

How to add object literal within object literal [duplicate]

This question already has an answer here: How can I add a key/value pair to a JavaScript object literal? 11 answers Assuming I have an object literal that looks like this: C = {A:a,B:b,

String to Object literal

Is it possible to convert a string var: data=data1,data2,data3,data4 to an object literal data={ data1:data2, data3:data4 } Thank you!

Answers

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

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

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.

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

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() {
    var o = {
        a: 5,
        b: 6
    };
    o.c = o.a + o.b;
    return o;
}();

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

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.

http://jsfiddle.net/jPNxY/1/

Simply instantiate an anonymous function:

var foo = new function () {
    this.a = 5;
    this.b = 6;
    this.c = this.a + this.b;
};

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

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

The key to all this is SCOPE.

You need to encapsulate the “parent” (parent object) of the property you want to define as it’s own instantiated object, and then you can make references to sibling properties using the key word this

It’s very, very important to remember that if you refer to this without first so doing, then this will refer to the outer scope… which will be the window object.

var x = 9   //this is really window.x
var bar = {
  x: 1,
  y: 2,
  foo: new function(){
    this.a: 5,
    this.b: 6,
    this.c = this.a + this.b;  // 11
  }
  z: this.x   // 9 (not 1 as you might expect, b/c *this* refers `window` object)
};

Creating new function on your object literal and invoking a constructor seems a radical departure from the original problem, and it’s unnecessary.

You cannot reference a sibling property during object literal initialization.

var x = { a: 1, b: 2, c: a + b } // not defined 
var y = { a: 1, b: 2, c: y.a + y.b } // not defined 

The simplest solution for computed properties follows (no heap, no functions, no constructor):

var x = { a: 1, b: 2 };

x.c = x.a + x.b; // apply computed property

The other answers posted here are better but here’s an alternative that:

  • Sets the value at initialization (not a getter, or derived, etc)
  • Doesn’t require any type of init() or code outside of the object literal
  • Is an object literal and not a factory function or other object creation mechanic.
  • Shouldn’t have any performance impact (except at initialization)

Self-executing anonymous functions and window storage

var foo = {
    bar:(function(){
        window.temp = "qwert";
        return window.temp;
    })(),
    baz: window.temp
};

The order is guaranteed (bar before baz).

It pollutes window of course, but I can’t imagine someone writing a script that requires window.temp to be persistent. Maybe tempMyApp if you’re paranoid.

It’s also ugly but occasionally useful. An example is when you are using an API with rigid initialization conditions and don’t feel like refactoring so the scoping is correct.

And it’s dry, of course.

just for the sake of thought – place object’s properties out of a timeline:

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

console.log(foo.c())

there are better answers above too. This is how I modified example code you questioned with.