0

I have a main function in javascript that is function a() { some code here } and I also have a child function in this main function that looks like

function a() {

    function b() {

        // some code here
    }

}

now I want to call the function b directly. then how to do this.

1
  • Functions declaring functions. How perverse! ;) Couldn't you simply cut/paste b() to have it on the same level as a() (global script level, therefore global visibility) ? Commented Mar 26, 2012 at 5:43

4 Answers 4

3

You can't. You can, however do something like:

function a() {

    this.b = function () {

        some code here
    }
}

And then call it like:

var x = new a();
a.b();

You can also create an object literal with your function:

var a = {
  b: function ()
     {
       //some code here
     }
};

And then just say:

a.b();

You could also create a property on the function object itself, and access it that way:

function a()
{
};

a.b = function ()
{
  //Some code here
};   

And then call it with:

a.b();
Sign up to request clarification or add additional context in comments.

Comments

1

You could try explicitly exposing b to the global object like this:

function a() {

    function b() {

        // some code here
    }

    window.exposed = b;
}

1 Comment

And if the host environment doesn't have a window object?
0

Don't declare function b inside of function a, just call it like so

function b() {
some code here
}

function a() {
b();
}

1 Comment

This is the obvious answer, but it's missing a discussion of how to access the locals of a from b i.e. how to hoist out the locals of a to make the closures equivalent.
0

There are many solutions here, the only one I think that will suit is to attach the function to the global object so it looks like a declared function. The only difference is that it won't be available until a runs:

function a() {

  // Protect against ES5 strict mode, assume function is called as global code
  if (typeof this !== undefined) {
    this.b = function() { /* whatever */ };
  }
}

or perhaps the following suits your coding style better:

function a() {

  function b() { /* whatever */};

  if (typeof this !== undefined) {
    this.b = b;
  }
}

Called simply as:

a();

then in ES3 or ES5 non-strict mode, it will work as expected. To overcome ES5 strict limitations where the above will result in a's this being undefined, call a as global code and set its this explicitly:

a.call(this);

or with some other suitable reference to the global object.

I have stayed away from using window since that is less reliable, not least because non–browser hosts will likely not have a window object.

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.