For convenience while debugging, I think it would be nice to print some custom string, rather than the default Object
that appears when logging an object to the console.
In the following example, see how an object called example
is marked by Object
when it is logged to the console, whereas window
is marked by Window
when it is logged to the console. I guessed that the __proto__["Symbol(Symbol.toStringTag)"]
property might be the way to go, since window
's is set to Window
. That didn't work, but maybe I'm just using it wrong.
That's because you're using the Symbol wrong -- you were on the right track. Symbol.toStringTag
is a special well-known Symbol used by Object#toString
to give you the console output, specifically the tag you're after. You can't wrap it in a string as you've done, or else you'll be literally setting the "Symbol.toStringTag"
property, not the actual Symbol:
const example = { key: "value" }; example.__proto__["Symbol.toStringTag"] = "Example"; console.log(example); //You set the literal "Symbol.toStringTag" property -- wrong
Instead, don't wrap it in quotes and actually set the Symbol:
const example = { key: "value" }; example.__proto__[Symbol.toStringTag] = "Example"; console.log(example);
Which produces (on Chrome):
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.