简体   繁体   中英

Is it possible to write a JS function with no access to global variables?

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
})()

I believe that no matter what the current scope is, there is always a way to get to the global object:

let ref_to_global = (function(){
  return this;
}).call(null);

Then one can access any property of the global object directly:

let value = ref_to_global["a"];

This means there is no way to make global scope inaccessible, if that was a question.

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