0

I want to access local variable of function but i can't change the function;

testFunction()
function testFunction()
{
    var localVarible = "Varible which i can't access";
}


console.log(localVarible)
4
  • 6
    You can't access them, that's the point of a LOCAL variable. If you need access to it return it from the function. Commented Nov 23, 2020 at 10:54
  • if you want to access the value of localVariable then declare it globally outside of the function and assign it the value inside the function. Commented Nov 23, 2020 at 10:56
  • 1
    What's the objective OP? Why do you need to change it inside the function? Why not just redeclare the function? Commented Nov 23, 2020 at 10:59
  • This is quite intentionally impossible and JavaScript's security model relies on this. However if you can connect a debugger you can access it (in chrome for example) via Debugger.pause and then listening to the Debugger.paused event which arrives with CallFrame objects with scope chains that have access to closures. You can also rewrite the source. Commented Nov 23, 2020 at 12:16

2 Answers 2

1

As noted in the comments, it's not directly possible and it would be useful to understand your objective here. But assuming you are tying to inject something over an existing page you can just re-declare the function, with some added code, e.g.:

var myGlobalVarible;
testFunction = function() {
    var localVarible = "Varible which i can't access";
    ...
    myGlobalVarible = localVarible;
}
console.log(myGlobalVarible);

You do need to include all the code of the original function to make this work; so it's not very clean!

Sign up to request clarification or add additional context in comments.

Comments

0

This issue will lead to interesting JavaScript topic "Closure"

Since you cannot access inner functions variable from outside. In JavaScript, all functions have access to the scope "above" them. JavaScript supports nested functions. Nested functions have access to the scope "above" them or the containing functions.

The closure is a way of JavaScript to implement accessing private intended variables problem (Like public properties to access private fields in C# programming language):

Following code is an example of the closure and should solve your problem.

var innerFunctionVariable = (function () {
    var localVariable = "Varible which i can't access";
    return function () {return localVariable;}
})();

console.log ( innerFunctionVariable());

Yes you are still declaring a global variable, but now it is clear to other developers that this global variable's intended job is ONLY accessing the "private" localVariable and nothing else.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.