64

I am trying to do something like this:

var obj = {
    a: 5,
    b: this.a + 1
}

(instead of 5 there is a function which I don't want to execute twice that returns a number)

I can rewrite it to assign obj.b later from obj.a, but can I do it right away during declaration?

serg
  • 109,619
  • 77
  • 317
  • 330
  • `javascript: var obj = {a: 5, b: this.a + 1}; alert(obj.b);` alerts NaN, so no. – Ben Jan 06 '11 at 18:52
  • 4
    Recently asked: http://stackoverflow.com/questions/4616202/self-references-in-object-literal-declarations, also see http://stackoverflow.com/questions/2787245/how-can-a-javascript-object-refer-to-values-in-itself – Roatin Marth Jan 06 '11 at 18:53

7 Answers7

49

No. this in JavaScript does not work like you think it does. this in this case refers to the global object.

There are only 3 cases in which the value this gets set:

The Function Case

foo();

Here this will refer to the global object.

The Method Case

test.foo(); 

In this example this will refer to test.

The Constructor Case

new foo(); 

A function call that's preceded by the new keyword acts as a constructor. Inside the function this will refer to a newly created Object.

Everywhere else, this refers to the global object.

Ivo Wetzel
  • 46,459
  • 16
  • 98
  • 112
14

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
ken
  • 3,650
  • 1
  • 30
  • 43
8

This should return the correct values:

function () {
   var aVar = 5;
   var bVar = aVar + 1;

return {
    a : aVar,
    b : bVar;  
}
}();
kemiller2002
  • 113,795
  • 27
  • 197
  • 251
5

As it turns out you can't reference an object inside another object unless the first one is a function. But you can do it this way.

    var obj = {
        a: 5
    }

    obj.b = obj.a + 1; // create field b in runtime and assign it's value

If you console.log(obj) you will have

   obj = {
        a: 5,
        b: 6
     } 

This way you keep the object literal structure for the remaining part of the code

Herbi Shtini
  • 2,002
  • 29
  • 34
2

No, in your example, the value of this doesn't refer to the object literal.

You'll need to assign a value to b after the object has been created in order to base it on another property in obj.

user113716
  • 318,772
  • 63
  • 451
  • 440
2

in chrome debugger

> var o = {a: 5, b: this.a+1}
undefined
> o.b
NaN
> o.a
5
hvgotcodes
  • 118,147
  • 33
  • 203
  • 236
1

No. this will take the same meaning as it would outside the definition.

fuzzyTew
  • 3,511
  • 29
  • 24