Alex Rivera | Logout

JavaScript - Declaring Global Scope for Nested Function?

Asked 2011-03-04T19:56:24.453
12

My attempts at giving global scope to a nested JavaScript function are not working:

//DECLARE FUNCTION B IN GLOBAL SCOPE
function B;

function A() {

    //DEFINE FUNCTION B INSIDE NEST
    B() {
        alert("function B is running");
    }
}

//CALL FUNCTION B FROM GLOBAL SCOPE
B();

This is just curiosity -- you are correct that I don't really have any good reason to want to do this.

TIA -- I don't have an SO account to respond to your answers...

Edit
Report

1 Answer

3

You can do something like this:

function outer() {
  function inner() {
    // ..
  }

  window['inner'] = inner;
}

It's a little icky to have a direct reference to "window", so you could do this (from the global context):

(function (global) {
  function inner() {
    // code code code ...
  }

  global['inner'] = inner;
})(this);
answered 2011-03-04T19:58:40.807

Your Answer