views:

44

answers:

3

I have an object structure/hierarchy like the one below:


var obj = {

    dimensions : {

        x : 100,
        y : 100,
        w : 300,
        h : 400,
        cmp : function () {

            return this.x + this.y;

        }

    },

    definition : {

        base : {

            rect1 : {

              // how do I get the value of dimensions.x ??
              // or, for that matter, is there a way I could call dimensions.cmp()?


            },

            rect2 : {
                // things go here
            }

        }

    }

};

 

My question is: Is to possible to get the value of dimensions.x from within the dimensions.definition.rect1 function?

A: 

obj.dimensions.x doesn't work?

Ionut Staicu
A: 

You can't really do that dynamically, the this value inside a function will point to the object there the function is bound as a property.

For example, if you invoke foo.bar.func();, the this value inside func will refer to the foo.bar object, there is no way to determine dynamically if this belongs to foo, without explicitly checking all properties of foo (and of course knowing beforehand where to check).

Remember that objects are handled as references, therefore an object can be referenced from many places.

Don't complicate yourself, find your members using the obj reference, keep it simple:

var obj = {
  dimensions : {
    x : 100,
    y : 100,
    //...
    cmp : function () {
      return this.x + this.y;
    }
  },
  definition : {
    base : {
      rect1 : {
       foo: function () {
        obj.dimensions.cmp();
        alert(obj.dimensions.x);
        }
      }
      //...
    }
  }
};
CMS
Thanks a lot! I was thinking this wouldn't be allowed for some reason. I had tried this before but it seems I was doing something silly. Thanks again.
bibhas
A: 

I'm not really sure what you are trying to accomplish, but if you are trying to make multiple instances of this type of object, you could try something like this:

function Structure() {
  this.dimensions = {
    x: 100,
    y: 100,
    w: 300,
    h: 400
  };
  function Rect(dimensions) {
    this.dimensions = dimensions;
    this.func = function() {
      alert(dimensions.x);
    }
  }
  this.definition = {
    base: {}
  };
  this.addRect = function(name) {
    this.definition.base[name] = new Rect(this.dimensions);
  };
};

var obj = new Structure();
obj.addRect('rect1');
obj.addRect('rect2');
obj.definition.base.rect1.func();
Alex M.