简体   繁体   中英

Javascript Calling a nested function from within itself

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?

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

function outer() {
    var inner;

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

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