我在使用 Proxy() 时遇到问题JavaScript 中的对象。
当我传入目标且没有处理程序时,此代码按预期工作:
const scope = new Proxy({a: 2, b: 2}, {});
with (scope) {
a + b;
}
但是,当我传入处理程序且没有目标时,它不起作用:
const scope = new Proxy({}, {get: function(){ return 2; }});
with (scope) {
a + b;
}
scope.a == 2 &&scope.b == 2
在这两种情况下都计算为 true
。
最佳答案
根据MDN ,以下是 JavaScript 如何解析 with
内的变量:
JavaScript looks up an unqualified name by searching a scope chain associated with the execution context of the script or function containing that unqualified name. The 'with' statement adds the given object to the head of this scope chain during the evaluation of its statement body. If an unqualified name used in the body matches a property in the scope chain, then the name is bound to the property and the object containing the property. Otherwise a ReferenceError is thrown.
这仅仅意味着 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 assignment,它也适用于动态 getter):
const scope = new Proxy({}, {get: function(){ return 2; }});
const {a, b} = scope;
console.log(a + b);
关于javascript - Proxy() block 作用域 - Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64431206/