For better knowledge of what a function is using, etc. Might also be faster for variable lookups if not accessing the global scope?
Suppose I have:
a = 5;
b = 5;
in the global scope. Is it possible to wrap the function below such that
function go() {
console.log(a);
}
would not have access to "a" and the global namespace and return
Uncaught ReferenceError: a is not defined
No, there is no way to completely prevent access to global variables. That said, you can provide it a different set of global variables: namely, run it in an iframe
. This isn’t bulletproof, though, since it could then just use window.parent
to access the global variables of the parent.
Yes. The example below is straight from MDN eval.
You could try this IF you could wrap your entire codebase in a single wrapper function so that all your objects and functions fall into local scope. (I am not sure how practicable this is but it works in Chrome and Firefox)
(function() {
var x = 2, y = 4;
function range(a,b){return [a,b];}
console.log("DIRECT", eval("x + y"), eval("range(3,4)")); // Direct call, uses local scope, result is 6
var geval = eval;
console.log("INDIRECT", geval("x + y"), geval("range(3,4)")); // Indirect call, uses global scope, throws ReferenceError because `x` is undefined
})()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With