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;
};
This technique works:
Create helper function to run a function in an isolated scope
you might also have some luck with the JavaScript
with
operator