简体   繁体   中英

How do you access an nested inner function from another outer function in JavaScript?

Please have a look at the following JavaScript snippet of code. This has to do with function scoping and hoisting in javascript. I can't call window.innermost() as it is undefined as it's not in scope.

Anyone know another way besides attaching it to the windows object. Windows Object still doesn't work in this case.

function outer(){
    function callback() { 
        window.innermost = function() {
            alert("hello from inner most")
        }
    }
}

(function caller() {
     window.innermost();  // this is undefined
}());

You would have to call both the outer and the callback:

function outer(){
    var callback = function() { 
        window.innermost = function() {
            alert("hello from inner most")
        }
    }
    callback(); // Call Callback
}
outer(); // Call outer

(function caller() {
     window.innermost();  // should work
}());

If both of these functions are not called before you run the anonymous function, then the window.innermost won't be defined (or undefined if you will).

Also, notice that I set callback as a variable, which is an alternative way of defining a function within a function.

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