javascript: scoping and accessing nested entities

75 views Asked by At

If we have this setup:

if (typeof(A) === 'undefined')
    A = {};

A.B = new function () {
   ....
   this.C = function () {
      ....
   }
}

what are some standard ways of accessing the C function from the outermost context (scope) ? I do have access to js sources so I can modify them accordingly.

2

There are 2 answers

0
Dinesh Patra On

You should not use new function(){} . Reason: Deathmatch: Self Executing Anonymous Function -vs- "new function"

But anyway as you have not wrote this code, you are just editing an plugin file, so you can access C using A.B.C()

    <script>
        if (typeof(A) === 'undefined')
            A = {};

        A.B = new function () {
            this.C = function () {
                alert("I am c");
            }
        }

        A.B.C();
    </script>
0
yvesmancera On

With only the code provided here, A is a global variable, so you can access it within any scope as A.B.C();

if(typeof(A) === 'undefined') {
   A = {};
}
A.B = function() {

    this.C = function() {
        alert('A.B.C was called');
    };
};

A.B.C();