Javascript Calling a nested function from within itself

1k Views Asked by At

If I run the following...

function outer(){
    function inner(){
    }

    inner();
}

inner will run the first time as expected.


If I then try to run the following...

function outer(){
    function inner(){
        inner();
    }

    inner();
}

inner will again run the first time as expected, but then fails at any subsequent attempts, returning the error: ReferenceError: inner is not defined


If I expose the function to the global namespace it will work again...

function outer(){
    function inner(){
        inner();
    }

    window.inner = inner;
    inner();
}

Is there a way to reference the nested function from within itself WITHOUT adding it to the global namespace?

1

There are 1 best solutions below

2
On BEST ANSWER

You can assign the function to a local variable within the execution scope

function outer() {
    var inner;

    inner = function () {
        inner();
    }
    inner();
}