简体   繁体   中英

call a function in javascript as global function

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.

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();

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

function a() {

    function b() {

        // some code here
    }

    window.exposed = b;
}

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

function b() {
some code here
}

function a() {
b();
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM