阻止JavaScript继承范围

Ale*_*lls 5 javascript closures lexical-closures node.js

我正在寻找一种奇特的方法来防止关闭继承周围的scrope.例如:

let foo = function(t){

  let x = 'y';

  t.bar = function(){

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

  });

};
Run Code Online (Sandbox Code Playgroud)

我知道防止共享范围的方法只有两种:

(1)使用阴影变量:

let foo = function(t){

  let x = 'y';

  t.bar = function(x){

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

  });

};
Run Code Online (Sandbox Code Playgroud)

(2)将函数体放在其他地方:

  let foo = function(t){

      let x = 'y';

      t.bar = createBar();

    };
Run Code Online (Sandbox Code Playgroud)

我的问题是 - 有没有人知道第三种方法可以防止在JS中继承范围?一些奇特的东西很好.

我认为唯一可行的是vm.runInThisContext()Node.js.

让我们使用我们的想象力一秒钟,并想象JS有一个私有关键字,这意味着该变量仅对该函数的范围是私有的,如下所示:

  let foo = function(t){

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

      t.bar = function(){

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

      });

    };
Run Code Online (Sandbox Code Playgroud)

和IIFE不会工作:

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;
};
Run Code Online (Sandbox Code Playgroud)

gue*_*314 6

您可以使用块范围

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();
Run Code Online (Sandbox Code Playgroud)

  • 好吧,我会被诅咒 (3认同)

Ale*_*lls 1

该技术的工作原理是:

创建辅助函数以在隔离范围内运行函数

 const foo = 3;

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

你也可能对 JavaScriptwith运算符有一些运气