我正在寻找一种花哨的方法来防止闭包继承周围的作用域。例如:
我的问题是 - 有没有人知道JS中防止闭包继承范围的第三种方法?可以使用一些高级方法。
我认为唯一可能起作用的是Node.js中的vm.runInThisContext()。
让我们想象一下,假设JS有一个private关键字,这意味着该变量仅对该函数的范围私有,例如:
let foo = function(t){
let x = 'y';
t.bar = function(){
console.log(x); // => 'y'
});
};
我知道的只有两种方法可以防止共享作用域:
(1) 使用影子变量:
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();
};
我的问题是 - 有没有人知道JS中防止闭包继承范围的第三种方法?可以使用一些高级方法。
我认为唯一可能起作用的是Node.js中的vm.runInThisContext()。
让我们想象一下,假设JS有一个private关键字,这意味着该变量仅对该函数的范围私有,例如:
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;
};