[英]Prevent JavaScript closure from inheriting scope
I am looking for a fancy way to prevent a closure from inheriting surrounding scrope. 我正在寻找一种奇特的方法来防止关闭继承周围的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: (1)使用阴影变量:
let foo = function(t){
let x = 'y';
t.bar = function(x){
console.log(x); // => '?'
});
};
(2) Put the function body somewhere else: (2)将函数体放在其他地方:
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? 我的问题是 - 有没有人知道第三种方法可以防止在JS中继承范围? Something fancy is fine.
一些奇特的东西很好。
The only thing that I think could possibly work is vm.runInThisContext()
in Node.js. 我认为唯一可行的是Node.js中的
vm.runInThisContext()
。
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: 让我们使用我们的想象力一秒钟,并想象JS有一个私有关键字,这意味着该变量仅对该函数的范围是私有的,如下所示:
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: 和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;
};
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();
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 您还可能有一些运气使用JavaScript
with
运营商
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.