2

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.

1

2 Answers 2

4

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

4 Comments

I've updated my answer. You shouldn't downvote answers if you change your question.
Hmm, this would be a possible solution but hard to integrate (I would have to rewright all my Backbone.Model implementations. Maybe there will come another answer. PS: I didn't downvote...
@dev.pus Instead of creating new closure you can simply create a copy of myObject variable that wouldn't change. This is ugly, but would work. P.S. Sorry for suspecting you :)
Hmm, I will wait a bit with the final answer mark but it seems that I will have to refactor a lot using closures :)
0

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

1 Comment

He says in his question that As you see I want to get myObject.attributes.name from an nested part of the object without having to observe the value. I guess he wouldn't even ask this question if this solution was acceptable

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.