1

I've looked through the docs on Proxies, and there is a long list of function properties which can be overridden. Unfortunately, none of them explicitly mention a link to console.log(), and I can't infer which ones console.log() might interact with.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy

I've also seen this Stack Overflow question (Javascript Proxy and spread syntax, combined with console.log) which seems to show something similar to what I'm looking for, but more targeted at getting information about a property than the way it's displayed in console.

The issue is, whenever I console.log my proxies, I get output like this:

Proxy { <target>: {…}, <handler>: {…} }

Further, my target is (in my case) totally empty.

const foo = { foo: "foo string" };
const bar = { bar: "bar string" };

let currentObj = foo;

const proxy = new Proxy({}, {
  get: (_, prop) => currentObj[prop],
});

console.log(proxy.foo);
console.log(proxy); // would like this to be { foo: "foo" }

currentObj = bar;
console.log(proxy.bar);
console.log(proxy); // would like this to be { bar: "bar" }

So, in order to make this code possible to debug, I need some way to tell console.log what object to output.

Is it possible to override some aspect of a Proxy handler such that console.log() will output arbitrary, use-case specific data?

Seph Reed
  • 8,797
  • 11
  • 60
  • 125
  • You cannot overwrite how any object is displayed in the console - you can't do it for proxies either. – Bergi Jul 15 '19 at 18:44
  • I assume you're on the browser, using chrome devtools for `console.log`? – Bergi Jul 15 '19 at 18:46
  • I'm making a tool for others to use, so I'm trying not to be browser specific. But, my case is FF devtools. – Seph Reed Jul 15 '19 at 19:02

1 Answers1

0

You could override the toString method and log your object with its toString() method.

Or you could provide a different view-specific log function such as oob.log => () => obj.name

ErocCatlun
  • 83
  • 1
  • 7