javascript - Proxy() block 作用域 - Javascript

标签 javascript node.js

我在使用 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/

相关文章:

node.js - 在 Express js 中引导后获取连接

javascript - 在 jupyter 笔记本中使用匹配替换查找和替换实用程序

javascript - react类中的成员变量引用为 "shared"

javascript - 使用 JavaScript 加密模块代替 SSL/HTTPS

javascript - 当 JSONP 数据改变时

javascript - v-for for 作为 props 传递的数组会引发错误

node.js - ElasticSearch/Node :按匹配项删除项目

javascript - 使用从客户端收到的谷歌授权代码在服务器端javascript(nodejs)上获取访问 token

javascript - 为什么我在浏览器中看不到我的应用程序渲染(Marionette.js 教程)?

javascript - Node.js 和 XAMPP 有什么区别