Proxy()块作用域-Javascript



我在使用Javascript中的Proxy((对象时遇到问题。

当我传入一个目标而没有处理程序时,此代码按预期工作:

const scope = new Proxy({a: 2, b: 2}, {});
with (scope) {
a + b;
}

然而,当我传入一个处理程序而没有目标时,它不起作用:

const scope = new Proxy({}, {get: function(){ return 2; }});
with (scope) {
a + b;
}

CCD_ 1在这两种情况下都评估为CCD_。

根据MDN,以下是JavaScript如何解析with:中的变量

JavaScript通过搜索作用域链查找不合格名称与脚本或函数的执行上下文关联包含该不合格名称。"with"语句添加给定的在评估其声明正文。如果正文中使用的非限定名称与属性,则名称绑定到该属性以及包含该属性的对象。否则ReferenceError抛出。

这只是意味着with将适用于scope的静态属性,但不适用于您创建的动态getter。

这是一个简单的测试,将有助于确定属性是否在with中可用:

const working = new Proxy({a: 2, b: 2}, {});
console.log('a' in working);
const notWorking = new Proxy({}, {get: function(){ return 2; }});
console.log('a' in notWorking);

此外,with也被弃用,这是从对象中提取属性的现代方法(它被称为Destructuring赋值,也适用于动态getter(:

const scope = new Proxy({}, {get: function(){ return 2; }});
const {a, b} = scope;
console.log(a + b);

最新更新