2

I have an JavaScript object defined as following...

    var f = {
        test: 'myTestContent',
        app: {
            base: {
                action: function () {
                    alert(test);
                }            
            }
        }
    };

    f.app.base.action();

The problem is that I cannot access the test variable as defined in the f instance. Is it possible to access variables in this context from nested objects?

At the moment I get test is undefined. Any suggestions? Thanks!

4
  • Try f.test (BTW -- test is not a global variable) Commented Oct 23, 2012 at 21:41
  • 1
    Correct. test is actually not a variable–it is a property of the object stored in the variable f. Commented Oct 23, 2012 at 21:42
  • There's no way to automatically get access to a "parent" object from a method of the "child" (because really although the "parent" has a reference to the "child" it doesn't actually own it - other objects could also have references to the same "child"). test isn't global the way your question sort of implies, it is a property of f so you can say f.test. Commented Oct 23, 2012 at 21:43
  • Is is somehow possible to define test to be global. Maybe another construction of defining the f instance? Commented Oct 24, 2012 at 17:43

2 Answers 2

4

test isn't defined globally. You'd have to use the proper reference:

alert(f.test);

Should work.

Sign up to request clarification or add additional context in comments.

Comments

2

test is not a global variable, rather it is a property of f. So you want:

var f = {
    test: 'myTestContent',
    app: {
        base: {
            action: function () {
                alert(f.test);  // Notice this line.
            }            
        }
    }
};

f.app.base.action();

Access it just like you access f.app on the last line.

2 Comments

"f, which is global" - unless the code in the question is inside a function. But yes, f.test will work either way.
I could pass the parent object to the child elements, but I'm trying to find a better solution for that. See example bellow of my usage... The problem is when creating copies of such an instance where the test parameter is not the same...

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.