From dfb353b882b580448e96fe7330ea1f8da527f3f5 Mon Sep 17 00:00:00 2001 From: raisinten Date: Mon, 9 Nov 2020 19:52:20 +0530 Subject: [PATCH] util: fix to inspect getters that access this Fixes: https://github.com/nodejs/node/issues/36045 Co-authored-by: Antoine du Hamel PR-URL: https://github.com/nodejs/node/pull/36052 Reviewed-By: Anna Henningsen Reviewed-By: Antoine du Hamel Reviewed-By: Rich Trott --- lib/internal/util/inspect.js | 8 +++-- ...est-util-inspect-getters-accessing-this.js | 30 +++++++++++++++++++ 2 files changed, 35 insertions(+), 3 deletions(-) create mode 100644 test/parallel/test-util-inspect-getters-accessing-this.js diff --git a/lib/internal/util/inspect.js b/lib/internal/util/inspect.js index cf2f32accaedd9..f6b60ba872c67f 100644 --- a/lib/internal/util/inspect.js +++ b/lib/internal/util/inspect.js @@ -46,6 +46,7 @@ const { ObjectPrototypePropertyIsEnumerable, ObjectSeal, ObjectSetPrototypeOf, + ReflectApply, RegExp, RegExpPrototypeToString, Set, @@ -628,7 +629,7 @@ function addPrototypeProperties(ctx, main, obj, recurseTimes, output) { continue; } const value = formatProperty( - ctx, obj, recurseTimes, key, kObjectType, desc); + ctx, obj, recurseTimes, key, kObjectType, desc, main); if (ctx.colors) { // Faint! output.push(`\u001b[2m${value}\u001b[22m`); @@ -1678,7 +1679,8 @@ function formatPromise(ctx, value, recurseTimes) { return output; } -function formatProperty(ctx, value, recurseTimes, key, type, desc) { +function formatProperty(ctx, value, recurseTimes, key, type, desc, + original = value) { let name, str; let extra = ' '; desc = desc || ObjectGetOwnPropertyDescriptor(value, key) || @@ -1699,7 +1701,7 @@ function formatProperty(ctx, value, recurseTimes, key, type, desc) { (ctx.getters === 'get' && desc.set === undefined) || (ctx.getters === 'set' && desc.set !== undefined))) { try { - const tmp = value[key]; + const tmp = ReflectApply(desc.get, original, []); ctx.indentationLvl += 2; if (tmp === null) { str = `${s(`[${label}:`, sp)} ${s('null', 'null')}${s(']', sp)}`; diff --git a/test/parallel/test-util-inspect-getters-accessing-this.js b/test/parallel/test-util-inspect-getters-accessing-this.js new file mode 100644 index 00000000000000..3d185b134e852d --- /dev/null +++ b/test/parallel/test-util-inspect-getters-accessing-this.js @@ -0,0 +1,30 @@ +'use strict'; + +require('../common'); + +// This test ensures that util.inspect logs getters +// which access this. + +const assert = require('assert'); + +const util = require('util'); + +class X { + constructor() { + this._y = 123; + } + + get y() { + return this._y; + } +} + +const result = util.inspect(new X(), { + getters: true, + showHidden: true +}); + +assert.strictEqual( + result, + 'X { _y: 123, [y]: [Getter: 123] }' +);