2334sdfsdf
2334sdfsdf

Reputation:

scope of returned object in javascript function

How do I access 'a' below?

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

Upvotes: 3

Views: 2251

Answers (4)

Chris MacDonald
Chris MacDonald

Reputation: 6136

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

Upvotes: 0

annakata
annakata

Reputation: 75854

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

Upvotes: 4

Mesh
Mesh

Reputation: 6442

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

Upvotes: 1

Tomalak
Tomalak

Reputation: 338248

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;
};

Upvotes: 8

Related Questions