Javascript object scope

How do I access the "a" below?

var test = function () {
     return {
        'a' : 1,
        'b' : this.a + 1  //doesn't work
    };
};
+3
source share
4 answers

You cannot do this. When you are in the process of constructing an object (what you are actually using with curly curly braces), there is no way to access its properties before creating it.

var test = function () {
  var o = {};
  o['a'] = 1;
  o['b'] = o['a'] + 1;
  return o;
};
+8
source
var t = function () 
        {
            return new x();
        };

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

abstract layer

edited for formatting, and noting that this is an offset from OLN

+4
source

You cannot Object Literal Notion does not support this access

+1
source
var test = function () {
    //private members
    var a = 1;
    var b = a + 1;
    //public interface
    return {
        geta : function () {
            return a;
        },
        getb : function () {
            return b;
        }
    }
}();
0
source

All Articles