3

How do I access 'a' below?

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

4 Answers 4

8

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;
};
Sign up to request clarification or add additional context in comments.

Comments

4
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

Comments

1

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.