如何在JavaScript函数外部访问其内部的变量?
I wrote the following code in JavaScript:
function testing() { var test = function() { console.log("hi"); }; return test; } testing.test;I tried to access the inner
testvariable viatesting.test, but it doesn't work. How can I access this inner variable from outside the function?
Solution Options
Let's start by clarifying why your current attempt fails: the test function is declared inside testing's local scope, so it's not exposed as a property of the testing function itself, nor is it accessible globally by default. Here are three practical ways to fix this:
1. Attach the inner function as a property to the outer function
You can directly assign test to the testing function object, which lets you access it exactly the way you tried with testing.test:
function testing() { // Assign the inner function as a property of the outer function testing.test = function() { console.log("hi"); }; return testing.test; } // Call testing() once to initialize the property testing(); // Now you can access and invoke it testing.test(); // Logs "hi"
If you want the property available without calling testing() first, define it outside the function's execution scope:
function testing() { return testing.test; } // Define the property upfront testing.test = function() { console.log("hi"); }; testing.test(); // Works immediately, no prior call to testing() needed
2. Return an interface object to encapsulate and expose inner values
If you prefer to keep internal state private but still expose controlled access, return an object with methods that interact with the inner function:
function testing() { var test = function() { console.log("hi"); }; // Return an object that acts as a public interface return { // Method to get the inner function getTest: function() { return test; }, // Method to call the inner function directly runTest: function() { test(); } }; } // Create an instance of the interface const testWrapper = testing(); testWrapper.getTest()(); // Logs "hi" testWrapper.runTest(); // Also logs "hi"
This is a classic encapsulation pattern, great for hiding implementation details while exposing necessary functionality.
3. Capture the returned inner function directly
Since your original testing function already returns the test function, you just need to store the result of calling testing():
function testing() { var test = function() { console.log("hi"); }; return test; } // Capture the returned inner function const myTestFunction = testing(); // Invoke it whenever you want myTestFunction(); // Logs "hi"
This works thanks to JavaScript closures—even after testing() finishes executing, the returned function retains access to its original scope (and the test function inside it).
Pick the approach that fits your use case: option 1 for a static property on the outer function, option 2 for encapsulated modules, option 3 for the simplest direct access.
内容的提问来源于stack exchange,提问作者Bidhan Sarkar

