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)
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!
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.
localVariablethen declare it globally outside of the function and assign it the value inside the function.Debugger.pauseand then listening to theDebugger.pausedevent which arrives withCallFrameobjects with scope chains that have access to closures. You can also rewrite the source.