tags:

views:

119

answers:

4

How do I access 'a' below?

var test = function () {
     return {
        'a' : 1,
        'b' : this.a + 1  //doesn't work
    };
};
+8  A: 

You can't do it this way. When you are in the process of constructing an object (that's what you actually do using the curly braces), there is no way to access it's properties before it is constructed.

var test = function () {
  var o = {};
  o['a'] = 1;
  o['b'] = o['a'] + 1;
  return o;
};
Tomalak
+1  A: 

You can't Object Literal Notion does not support this access

Adrian
+4  A: 
var t = function () 
     {
      return new x();
     };

var x = function ()
     {
      this.a = 1;
      this.b = this.a + 1; //works
     }

abstract a layer

edited for formatting, and noting that this is shifting from OLN

annakata
A: 
var test = function () {
    //private members
    var a = 1;
    var b = a + 1;
    //public interface
    return {
        geta : function () {
            return a;
        },
        getb : function () {
            return b;
        }
    }
}();
Chris MacDonald