为什么这会抛出ReferenceError?
var p = new Proxy({}, {
get: function(target, name) {
return `hello world ${name}`;
}
});
with (p) { console.log(a) }
Run Code Online (Sandbox Code Playgroud)
未捕获的引用错误:a 未定义
这段代码非常愚蠢。然而它提出的问题非常有趣。事实证明你可以让它发挥作用!has您需要一种方法来使用代理上的方法告诉 javascript 对象中哪些变量可用。此外,由于某些原因,符号无法隐式转换为字符串。因此,为了让这段代码“工作”,你需要这样的东西。
var p = new Proxy({}, {
//we need to identify what elements are available.
//this overloads the in operator eg ("foo" in obj)
has:function(target,name){
//if we just returned true we would override everything
//and we need to get to the console
return name!="console";
},
get: function(target, name) {
//for some reason the toString is mandatory don't know why
//you get "TypeError: Cannot convert a Symbol value to a string" otherwise
return "Hello world "+name.toString();
}
});
with (p) { console.log(abc) }
Run Code Online (Sandbox Code Playgroud)