Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent JavaScript closure from inheriting scope

I am looking for a fancy way to prevent a closure from inheriting surrounding scrope. For example:

let foo = function(t){

  let x = 'y';

  t.bar = function(){

    console.log(x); // => 'y'

  });

};

there are only two ways I know of preventing sharing scope:

(1) Use shadow variables:

let foo = function(t){

  let x = 'y';

  t.bar = function(x){

    console.log(x); // => '?'

  });

};

(2) Put the function body somewhere else:

  let foo = function(t){

      let x = 'y';

      t.bar = createBar();

    };

My question is - does anyone know of a 3rd way to prevent closures from inheriting scope in JS? Something fancy is fine.

The only thing that I think could possibly work is vm.runInThisContext() in Node.js.

Let's use our imaginations for a second, and imagine JS had a private keyword, which meant the variable was private only to that function's scope, like this:

  let foo = function(t){

      private let x = 'y';  // "private" means inaccessible to enclosed functions

      t.bar = function(){

        console.log(x); // => undefined

      });

    };

and IIFE won't 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;
};
like image 452
Alexander Mills Avatar asked Jul 22 '17 23:07

Alexander Mills


2 Answers

You can use block scope

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();
like image 87
guest271314 Avatar answered Nov 06 '22 06:11

guest271314


This technique works:

Create helper function to run a function in an isolated scope

 const foo = 3;

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

you might also have some luck with the JavaScript with operator

like image 32
Alexander Mills Avatar answered Nov 06 '22 06:11

Alexander Mills