Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
handle the case toPrimitive is defined in prototype
  • Loading branch information
islandryu committed Apr 12, 2025
commit 140a6f28cff5ceb9d75c313547425aaa3a492553
9 changes: 5 additions & 4 deletions lib/internal/util/inspect.js
Original file line number Diff line number Diff line change
Expand Up @@ -2160,7 +2160,7 @@ function hasBuiltInToString(value) {
}
value = proxyTarget;
}
// Count objects that have neither a `toString` function nor a `Symbol.toPrimitive` function.
// Count objects without `toString` and `Symbol.toPrimitive` function as built-in.
if (typeof value.toString !== 'function' && typeof value[SymbolToPrimitive] !== 'function') {
Comment thread
BridgeAR marked this conversation as resolved.
Outdated
return true;
}
Expand All @@ -2175,12 +2175,13 @@ function hasBuiltInToString(value) {
return false;
}

// Find the object that has the `toString` property as own property in the
// prototype chain.
// Find the object that has the `toString` property or `Symbol.toPrimitive` property
// as own property in the prototype chain.
let pointer = value;
do {
pointer = ObjectGetPrototypeOf(pointer);
} while (!ObjectPrototypeHasOwnProperty(pointer, 'toString'));
} while (!ObjectPrototypeHasOwnProperty(pointer, 'toString') &&
!ObjectPrototypeHasOwnProperty(pointer, SymbolToPrimitive));

// Check closer if the object is a built-in.
const descriptor = ObjectGetOwnPropertyDescriptor(pointer, 'constructor');
Expand Down
22 changes: 22 additions & 0 deletions test/parallel/test-util-format.js
Original file line number Diff line number Diff line change
Expand Up @@ -299,6 +299,28 @@ assert.strictEqual(util.format('%s', -Infinity), '-Infinity');
assert.strictEqual(util.format('%s', symbol), util.inspect(symbol));
}

{
function hasToStringButNoToPrimitive() {}

hasToStringButNoToPrimitive.prototype.toString = function() {
return 'hasToStringButNoToPrimitive';
};

const obj = new hasToStringButNoToPrimitive();
assert.strictEqual(util.format('%s', obj.toString()), 'hasToStringButNoToPrimitive');
}

{
function hasToPrimitiveButNoToString() {}

hasToPrimitiveButNoToString.prototype[Symbol.toPrimitive] = function() {
return 'hasToPrimitiveButNoToString';
};

const obj = new hasToPrimitiveButNoToString();
assert.strictEqual(util.format('%s', obj[Symbol.toPrimitive]()), 'hasToPrimitiveButNoToString');
}

// JSON format specifier
assert.strictEqual(util.format('%j'), '%j');
assert.strictEqual(util.format('%j', 42), '42');
Expand Down