简体   繁体   中英

Return function not being found in global scope

var setup = function(){
    console.log("xyz");
    return function goBack(){
        console.log("It's actually abc");
    }
}

Now, on calling setup() in the global scope, "xyz" is being shown in the console, but the returning function(goBack) is not being appended in the global scope. Shouldn't I be able to access goBack from the global scope once I execute setup() ?

setup is returning a function.

To access it, first call var result = setup() . Now you have goBack stored in the result variable.

You can now use result() to call goBack from outside the scope of setup .

no, you're returning it from setup - the name goBack is irrelevant. You would need to call it on the return value from setup :

var foo = setup();
foo();// calls the function youve named `goBack`
// goBack() does not exist here.

You can access this function goBack like this

var setup = function(){
console.log("xyz");
return function goBack(){
    console.log("It's actually abc");
}(); // IIFE here
}

setup(); // returns xyz , its actually abc

As you see here , I have made the goBack into an IIFE and called setup() in the global scope.

All you needed to do was invoke the function that you were returning.

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