Jeong SangCheol
Jeong SangCheol

Reputation: 113

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;

Upvotes: 5

Views: 3778

Answers (2)

Donal
Donal

Reputation: 32713

You need to wrap everything in a closure:

    (function() {
        var window = 'foo';
        function privateFunction(){
            return window;
        }
    
        console.log(privateFunction());
    })();

Upvotes: 4

Bergi
Bergi

Reputation: 664548

Shadow the global variable by a local one:

function privateFunction() {
    var window;
    return window; // not the Window, but undefined now
}

Upvotes: 4

Related Questions