util: improve Symbol.toStringTag handling

Only special handle `Symbol.toStringTag` if the property is not
enumerable or not the own property of the inspected object.

PR-URL: https://github.com/nodejs/node/pull/27342
Reviewed-By: Benjamin Gruenbaum <benjamingr@gmail.com>
Reviewed-By: Anna Henningsen <anna@addaleax.net>
This commit is contained in:
Ruben Bridgewater 2019-04-22 06:13:16 +02:00 committed by Daniel Bevenius
parent 80c0b89bbb
commit 2f1add18a4
2 changed files with 22 additions and 3 deletions

View File

@ -574,8 +574,15 @@ function formatRaw(ctx, value, recurseTimes, typedArray) {
const constructor = getConstructorName(value, ctx);
let tag = value[Symbol.toStringTag];
if (typeof tag !== 'string')
// Only list the tag in case it's non-enumerable / not an own property.
// Otherwise we'd print this twice.
if (typeof tag !== 'string' ||
tag !== '' &&
(ctx.showHidden ? hasOwnProperty : propertyIsEnumerable)(
value, Symbol.toStringTag
)) {
tag = '';
}
let base = '';
let formatter = getEmptyFormatArray;
let braces;

View File

@ -1267,8 +1267,20 @@ util.inspect(process);
{
// @@toStringTag
assert.strictEqual(util.inspect({ [Symbol.toStringTag]: 'a' }),
"Object [a] { [Symbol(Symbol.toStringTag)]: 'a' }");
const obj = { [Symbol.toStringTag]: 'a' };
assert.strictEqual(
util.inspect(obj),
"{ [Symbol(Symbol.toStringTag)]: 'a' }"
);
Object.defineProperty(obj, Symbol.toStringTag, {
value: 'a',
enumerable: false
});
assert.strictEqual(util.inspect(obj), 'Object [a] {}');
assert.strictEqual(
util.inspect(obj, { showHidden: true }),
"{ [Symbol(Symbol.toStringTag)]: 'a' }"
);
class Foo {
constructor() {