无法直接访问target对象时,如何通过Proxy拦截Array的push方法获取它
拦截Array.push方法并获取嵌套的target对象
现有一个嵌套结构的target对象,已通过Proxy实现对Array类型push方法的拦截。要求在执行target.example.examples.push(1)时,通过该Proxy完成拦截校验,并将变量t赋值为target对象。注意:无法直接访问target对象,只能通过拦截push操作的Proxy来获取它。
实现代码
const target = { example: { examples: [] } }; let t; const handler = { apply(target, thisArg, argumentsList) { if (!t) { try { // 向上查找目标对象target if (typeof thisArg.parent?.parent === "object") { const temp = thisArg.parent.parent; // 通过属性特征验证是否为目标对象 if (temp.example?.examples) t = temp; } } catch (e) { console.error("发生错误:", e); } } // 执行原push方法 return Reflect.apply(target, thisArg, argumentsList); } }; // 用Proxy包装Array原型上的push方法 Array.prototype.push = new Proxy(Array.prototype.push, handler); // 触发拦截,此时t会被赋值为target target.example.examples.push(1);
关键逻辑说明
- 在Proxy的
apply拦截函数里,thisArg就是调用push的那个数组实例(也就是target.example.examples)。这里我们假设数组实例带有parent属性,指向它的父对象target.example,再往上一层的parent.parent就是外层的候选对象。 - 我们通过检查候选对象是否具备
example?.examples这个结构特征,来确认它就是我们要找的target,确认后就把它赋值给t。 - 最后调用
Reflect.apply执行原本的push方法,保证数组的正常添加功能不受影响。
内容的提问来源于stack exchange,提问作者bread
相关产品推荐
相关产品推荐

