作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
为什么会抛出 ReferenceError?
var p = new Proxy({}, {
get: function(target, name) {
return `hello world ${name}`;
}
});
with (p) { console.log(a) }
Uncaught ReferenceError: a is not defined
最佳答案
这段代码很傻。然而,它提出的问题非常有趣。事实证明你可以让它工作!您需要一种方法来使用代理上的 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) }
关于Javascript 代理和 With 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46081756/
我是一名优秀的程序员,十分优秀!