1

Can the outer's value be accessed from a function of the inner object? Is there a way?

var outer = {
    value: "1",
    inner: {
        getValue: function() {
            return value; // undefined
        }
    }
}

alert(outer.inner.getValue()); // fails

3 Answers 3

1

There is no way to refer to the containing object, as your "inner" object could have an infinite number of containing objects. You have to be explicit and give it a reference to the parent object.

var outer = { ... };

var inner = {
  parent: outer,
  getValue: function () { return this.parent.value() }
}
Sign up to request clarification or add additional context in comments.

Comments

1

What you can do is refer explicitly to outer object's property via it's reference, e.g.:

var outer = {
    value: "1",
    inner: {
        getValue: function() {
            return outer.value; // 1
        }
    }
}

alert(outer.inner.getValue());

However this solution is not so flexible.

Comments

0

You can't do this by javascript specifications. Maybe this way:

var outer = {
    value: "1",
    inner: (function(){
        var parent = this;
        return {
            getValue: function() {
                return parent.value;
            }
        }
    }).apply(outer)
}

Comments

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.