因此,我在尝试使用 Proxy 对象并尝试了解它们如何与扩展语法和解构混合时,我偶然发现了这种奇怪的行为:
const obj = {
origAttr: 'hi'
}
const handler = {
get(target, prop) {
console.log(prop);
return 1;
},
has(target, prop) {
return true;
},
ownKeys(target) {
return [...Reflect.ownKeys(target), 'a', 'b'];
},
getOwnPropertyDescriptor(target, key) {
return {
enumerable: true,
configurable: true
};
}
}
const test = new Proxy(obj, handler);
const testSpread = { ...test};
console.log('Iterate test');
// Works OK, output as expected
for (const i in test) {
console.log(i, ' -> ', test[i]);
}
console.log('Iterate testSpread');
// Also works OK, output as expected
for (const i in testSpread) {
console.log(i, ' -> ', testSpread[i]);
}
console.log('Here comes the unexpected output from console.log:');
console.log(test); // All attributes are 'undefined'
console.log(testSpread); // This is OK for some wierd reason
上述脚本输出(在节点 v10.15.1 上):
这是控制台日志的意外输出:
Symbol(nodejs.util.inspect.custom)
Symbol(Symbol.toStringTag)
Symbol(Symbol.iterator)
{ origAttr: undefined, a: undefined, b: undefined }
{ origAttr: 1, a: 1, b: 1 }
为什么console.log(test);输出显示对象的属性全部未定义?如果在调试某些东西时发生这种情况,可能会导致一些严重的头痛。
这是节点本身的错误还是console.log的实现中的错误?
好吧,我做了一些更多的挖掘,并将整个过程追溯到在我的代理对象上调用 Object.getOwnPropertyDescriptor 以获取其属性的值。
但在我的例子中,“value”属性显然是未定义的,因为我有一个 getOwnPropertyDescriptor 陷阱,它只指定可枚举和可配置的属性(从而可以迭代数组,将其与扩展运算符一起使用等)。 由于没有从 getOwnPropertyDescriptor 陷阱调用 get 陷阱的标准方法,因此恕我直言,这实际上无法修复。不过,如果被证明是错误的,那就很有趣了:)
嗯,正如 Bergi 在评论中指出的那样,有一个标准的方法。
也在文档中https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/handler/getOwnPropertyDescriptor#Parameters https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/handler/getOwnPropertyDescriptor#Parameters“这与处理程序绑定”
编辑我的代码以反映这一点。
演示 getOwnPropertyDescriptor 行为的代码如下:
const obj = {
origAttr: 'hi'
}
const handler = {
get(target, prop) {
return 1;
},
has(target, prop) {
return true;
},
ownKeys(target) {
return [...Reflect.ownKeys(target), 'a', 'b'];
},
getOwnPropertyDescriptor(target, key) {
return {
value: this.get(target, key),
enumerable: true,
configurable: true
};
}
}
const test = new Proxy(obj, handler);
const testSpread = { ...test
};
// Defined, due to trapped getOwnPropertyDescriptor which returns a value attribute
console.log(Object.getOwnPropertyDescriptor(test, 'origAttr'))
// Defined, because it is a regular object, not a proxy with a getOwnPropertyDescriptor trap
console.log(Object.getOwnPropertyDescriptor(testSpread, 'origAttr'))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)