Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS: How can I prevent access to the global variables do?

Is to disable the global variable in the function that I want.

I would make like Expenssion of Adobe After Effect

example code :

function privateFunction(){
    return window;
}

then normally :

result : Window Object

but I want then :

result : undefined

What should I do?

please help me

I want blocking global variable access in function;

like image 588
Jeong SangCheol Avatar asked Aug 21 '14 11:08

Jeong SangCheol


2 Answers

Shadow the global variable by a local one:

function privateFunction() {
    var window;
    return window; // not the Window, but undefined now
}
like image 137
Bergi Avatar answered Nov 14 '22 23:11

Bergi


You need to wrap everything in a closure:

    (function() {
        var window = 'foo';
        function privateFunction(){
            return window;
        }
    
        console.log(privateFunction());
    })();
like image 31
Donal Avatar answered Nov 14 '22 23:11

Donal