0

I am trying to set and later access a variable using object literal notation. I need to use this variable in subsequent code so I want to set it here just once.

When I run this code at jsFiddle, I get the error that HalfWidth is NaN. How do I set and access this variable from here?

var $LIST = {
  FullWidth: 120,
  HalfWidth: this.FullWidth / 2,
  exit: function () {}
};

alert($LIST.FullWidth);
alert($LIST.HalfWidth);

http://jsfiddle.net/7JcaQ/

Evik James
  • 10,335
  • 18
  • 71
  • 122

1 Answers1

3

this have zero relevance to your situation - it is only defines context object for method call. Additionally, you cannot reference $LIST in its own definition, because it doesn't exits until definition ends.

Write:

var $LIST = {
  FullWidth: 120,
  exit: function () {}
};
$LIST.HalfWidth = $LIST.FullWidth / 2

(For the note, you're getting NaN, because outside of method call this is most often refers to global object, which naturally, most often don't have any numeric value in its .FullWidth property. Dividing this by 2 produces NaN.)

Oleg V. Volkov
  • 21,719
  • 4
  • 44
  • 68