Prevent JavaScript closure from inheriting scope

2019-02-10 09:07发布

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;
};

2条回答
我只想做你的唯一
2楼-- · 2019-02-10 09:38

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

查看更多
家丑人穷心不美
3楼-- · 2019-02-10 09:50

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

查看更多
登录 后发表回答