gpt4 book ai didi

Javascript 代理和 With 语句

转载 作者:行者123 更新时间:2023-11-30 11:31:28 25 4
gpt4 key购买 nike

为什么会抛出 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com