Prevent JavaScript from being inherited

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); // => 'y' }); }; 

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'; // "private" means inaccessible to enclosed functions t.bar = function(){ console.log(x); // => undefined }); }; 

and IIFE will not work:

 let foo = function(t){ (function() { let x = 'y'; }()); console.log(x); // undefined (or error will be thrown) // I want x defined here t.bar = function(){ // but I do not want x defined here console.log(x); } return t; }; 
+5
source share
2 answers

This method works:

Create a helper function to run a function in an isolated area

  const foo = 3; it.cb(isolated(h => { console.log(foo); // this will throw "ReferenceError: foo is not defined" h.ctn(); })); 

you might also be lucky with the JavaScript with statement

+1
source

You can use the block area

 let foo = function(t) { { // `x` is only defined as `"y"` here let x = "y"; } { t.bar = function(x) { console.log(x); // `undefined` or `x` passed as parameter }; } }; const o = {}; foo(o); o.bar(); 
+5
source

Source: https://habr.com/ru/post/1270106/


All Articles