阻止JavaScriptclosuresinheritance范围
我正在寻找一种奇特的方法来防止封闭inheritance周围的sc。。 例如:
let foo = function(t){ let x = 'y'; t.bar = function(){ console.log(x); // => 'y' }); };
我知道防止共享范围的方式只有两种 :
(1)使用阴影variables:
let foo = function(t){ let x = 'y'; t.bar = function(x){ console.log(x); // => '?' }); };
(2)把函数体放在别的地方:
let foo = function(t){ let x = 'y'; t.bar = createBar(); };
我的问题是 – 有没有人知道的第三种方法,以防止在JSinheritance范围closures? 一些幻想是好的。
我认为唯一可能的工作是Node.js中的vm.runInThisContext()
。
让我们用我们的想象一下,想象JS有一个私人关键字,这意味着该variables是私人的,只有该function的范围,如下所示:
let foo = function(t){ private let x = 'y'; // "private" means inaccessible to enclosed functions t.bar = function(){ console.log(x); // => undefined }); };
和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; };
您可以使用块范围
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();