所以,我在玩 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的实现中的错误?