到目前为止,我已经将 ES6 代理理解为一种添加拦截的方法,以允许您向代码添加自定义行为。实现此代码片段以拦截对数组的推送,但它记录了额外的额外“被困!”推后 1',我不明白为什么。有谁知道为什么这样做?这是否意味着陷阱中的代码运行了两次?
const handler = {
set(target, propertyKey, value, receiver) {
console.log('trapped!', value);
return Reflect.set(target, propertyKey, value, receiver);
}
};
const p = new Proxy([], handler);
p.push('a')
最佳答案
它设置您要推送到的数组的长度和索引。这就是为什么它每次推送都会运行两次。
let handler = {
set(target, propertyKey, value, receiver) {
console.log(`set ${propertyKey} to ${value}`)
return Reflect.set(target, propertyKey, value, receiver);
}
};
const p = new Proxy([], handler);
p.push('a')
关于javascript - ES6 Proxy 记录了无法解释的额外值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48095587/