简体   繁体   中英

Is it possible to access private variable of javascript function

Suppose I have a JavaScript function. and it contain a variable x;

function A(){
   var x = 12+34;
}

Is it possible to access x from outside function x?

No , the ability to do so would not make any sense. Suppose we changed your function slightly and called it 3 times:

function x(n){
   var x = n+34;
}

x(1), x(2), x(3);

At this point, the function has run 3 times, so the variable x has been created 3 times — which x would you expect to be able to access? Then there's garbage collection; how could references and data be cleared from memory if the browser had to keep variables alive once they're no longer in scope?

If you want to, you can do something like this:

function x() {
    x.x = 12+34;
}
x();

or, if the variable will be static/constant as you have it

function x() { }
x.x = 12+34;

or finally, as others have pointed out, by declaring x under a different name outside of the function's scope:

var y;
function x() {
    y = 12+34;
}
x();

Yes, but not as scoped in your example above. You must use closure. Consider the following:

var x,
    A = function () {
        x = 12 + 34;
    };

In this manner you can access x from inside the function A. What is even better is that x has direct access to the private members of A and so can be used to leak private data outside of A.

You can not access it directly by its name, try removing 'var' from the variable declaration, as this should make the variables globals, or placing them outside the ready function. and return the value of x from the function.

You can do some thing like this:

$(document).ready(function() {    
        var x;
        function x(){
            x = 12+34;
            return x;
        }
        alert(x());
});

Here is its jsfiddle

Hope this helps.

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