I am looking for a fantastic way to prevent closure from inheriting the surrounding scrope. For instance:
let foo = function(t){ let x = 'y'; t.bar = function(){ console.log(x);
I know only two ways to prevent sharing:
(1) Use shadow variables:
let foo = function(t){ let x = 'y'; t.bar = function(x){ console.log(x);
(2) Put the function body in a different place:
let foo = function(t){ let x = 'y'; t.bar = createBar(); };
My question is: does anyone know of a 3rd way to prevent closure from region inheritance in JS? Something fantastic is in order.
The only thing that I think could work is vm.runInThisContext() in Node.js.
Let's use our fantasies for a second and suppose that JS has the private keyword, which means that the variable was closed only for this function scope, for example:
let foo = function(t){ private let x = 'y';
and IIFE will not work:
let foo = function(t){ (function() { let x = 'y'; }()); console.log(x);
source share