Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 859
Bryan Grace Avatar asked Jul 12 '15 19:07

Bryan Grace


2 Answers

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.

like image 169
icktoofay Avatar answered Sep 19 '22 03:09

icktoofay


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
})()
like image 26
Dinesh Avatar answered Sep 23 '22 03:09

Dinesh