[英]Javascript Proxies and With statements
为什么这会引发ReferenceError?
var p = new Proxy({}, {
get: function(target, name) {
return `hello world ${name}`;
}
});
with (p) { console.log(a) }
未捕获的ReferenceError:未定义
这段代码很愚蠢。 但是,它提出的问题非常有趣。 事实证明,您可以使它起作用! 您需要一种使用代理上的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) }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.