我正在为Get Object.getOwnPropertyDescriptors() from Javascript recursively, and flatten it创建一个递归函数。
这是密码:
let master = [];
function something (obj,str) {
if (Object(obj)===obj) {
pobj = Object.getOwnPropertyDescriptors(obj)
for (let kk in pobj) {
maststr = str;
//console.log(obj);
//console.log("line 8");
//console.log(kk);
if (master.includes(kk)||kk==="constructor"||kk==="globalThis"||kk==="global") { //circular reference // ||typeof obj[kk]==="function"
return;
} else {
maststr = str + "." + kk ;
console.log("line - 1st");
console.log(maststr);
console.log(kk);
console.log(pobj[kk]);
pobj[kk]["name"] = maststr;
master.push(pobj[kk]);
console.log("line - 2nd");
console.log(maststr);
if (maststr==="globalThis.Function.prototype.arguments"||maststr==="globalThis.Function.prototype.caller"
||maststr==="globalThis.Function.prototype.callee") continue;
something(obj[kk], maststr);
}
}
} else {
//master.push(obj);
return;
}
}
something(globalThis,"globalThis");
console.log(master);
它一直工作得很好,直到我到达Object.assign属性,奇怪的是它变成了undefined,并抛出了以下错误:
/Users/user/Documents/playground/playgroundtests_js/E16_2.js:19
pobj[kk]["name"] = maststr;
^
TypeError: Cannot set properties of undefined (setting 'name')
at something (/Users/user/Documents/playground/playgroundtests_js/E16_2.js:19:21)
at something (/Users/user/Documents/playground/playgroundtests_js/E16_2.js:25:4)
at Object.<anonymous> (/Users/user/Documents/playground/playgroundtests_js/E16_2.js:38:1)
at Module._compile (node:internal/modules/cjs/loader:1191:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1245:10)
at Module.load (node:internal/modules/cjs/loader:1069:32)
at Function.Module._load (node:internal/modules/cjs/loader:904:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
at node:internal/main/run_main_module:22:47
实际上,当我在抛出错误之前console.log这个属性时,它是未定义的。但是当我在节点REPL上测试Object.getOwnPropertyDescriptors(Object.assign)时,它返回了一个对象。
为什么会这样,我该如何解决?
1条答案
按热度按时间sr4lhrrt1#
还有几个循环依赖关系。如下所示:
1.内部错误
1.应用
1.对象