Created
January 16, 2022 00:27
-
-
Save narensulegai/1520cc3d73e47c7152367dad3bb09d89 to your computer and use it in GitHub Desktop.
Simple utitly function to inspect JavaScript a variable
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function printVar(ob, tc = 0) { | |
tc += 1 | |
const tabs = '\t'.repeat(tc) | |
const prototypes = (ob) => { | |
let res = '' | |
for (const e of Object.getOwnPropertyNames(ob.prototype)) { | |
if (e === 'constructor') { | |
res += e | |
} else { | |
res += log(ob.prototype[e], tc + 1) | |
} | |
} | |
return res | |
} | |
if (Function.prototype.isPrototypeOf(ob)) { | |
return ` f(${ob.name})\n${tabs}<prototype> ${ob.prototype === undefined ? 'Native' : prototypes(ob)}` | |
} | |
if (ob === Object.prototype) { | |
return "{Object.prototype}" | |
} | |
if (!Object.prototype.isPrototypeOf(ob)) { | |
return ob | |
} | |
let res = `\n${tabs}[${ob.constructor.name}]\n` | |
for (let p of Object.getOwnPropertyNames(ob)) { | |
res += `${tabs}${p}:${log(ob[p], tc + 1)}\n` | |
} | |
res += `${tabs}__proto__:${log(ob.__proto__, tc + 1)}` | |
return res | |
} | |
// Usage | |
console.log(log(new function Dog(){})) | |
// Prints | |
// [Dog] | |
// __proto__: | |
// [Dog] | |
// constructor: f(Dog) | |
// <prototype> constructor | |
// __proto__:{Object.prototype} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment