dev.pus
dev.pus

Reputation: 8139

javascript: Define reference in nested object to parent object

I have following object:

var myObject = {
    attributes: { name: "dev.pus", age: 29 },
    someInjectedObject: {
        name: "someComponent",
        action: function() {
            // do something
            return this.this.attributes.name; // this surely won't work :(
        }
    }
};

As you see I want to get myObject.attributes.name from an nested part of the object without having to observe the value.

How do I do this? How do I define a reference?

EDIT: A simple myObject.attributes isn't enough because myObject changes or better gets assigned to a new variable.

Upvotes: 2

Views: 1407

Answers (2)

Dmitry Osinovskiy
Dmitry Osinovskiy

Reputation: 10118

Create a closure around your object:

var myObject = (function() {
  var result = {
    attributes: { name: "dev.pus", age: 29 },
    someInjectedObject: {
      name: "someComponent",
      action: function() {
        // do something
        return result.attributes.name;
      }
    };
  };
  return result;
})();

Upvotes: 4

qwertymk
qwertymk

Reputation: 35274

You can do refer to myObject directly like this:

var myObject = {
    attributes: { name: "dev.pus", age: 29 },
    someInjectedObject: {
        name: "someComponent",
        action: function() {
            // do something
            return myObject.attributes.name; // this surely will work :(
        }
    }
};

alert(myObject.someInjectedObject.action());
​

DEMO

Upvotes: 0

Related Questions