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;
};
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With