7

Before, I would use the old convention of naming fields intended to be private with an _ suffix or prefix.

class X{
  constructor() {
    this.privateField_;
  }
  
  privateMethod_() {}
}

Now that real private accessibility is possible with the # symbol, I've been using them a bit.

class X{
  #privateField;

  #privateMethod() {}
}

But one situation I come across is needing to access these private members when debugging. But of course, they're private so I can't unless I write some debug-only wrapper/accessor, which isn't practical if I don't know ahead of time which fields/classes I need to debug. With the _ naming convention, it was easy to bypass intentionally.

Is there a way to bypass the private modifier when using chrome dev console, just like it allows you to use await outside of async blocks?

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
junvar
  • 11,151
  • 2
  • 30
  • 46
  • 2
    If you log the whole object to the console, you should be able to expand it and view all the properties that way. – Barmar Jan 25 '22 at 17:22
  • 2
    Thanks, you're right, I can see field values. But 1) I can't call methods, or 2) access functions on the private fields. – junvar Jan 25 '22 at 17:39
  • Private is private. You could define an override of `toString()` that allowed you to view the values of private fields, and of course you can define methods to be public or call them from public methods and observe their effects (a la unit testing). – Heretic Monkey Aug 24 '22 at 13:56
  • You can put a breakpoint in a public method and then call that method. When the debugger is paused on the breakpoint within the class, it allows you to access private members of that class. – Donald Duck Sep 10 '22 at 09:48

1 Answers1

3

A workaround is to place a breakpoint in the scope of the class definition (e.g. in a public method, then calling that method). While paused at the breakpoint, you can evaluate code in the debugger console that can access the private field.


And since Chrome 111, this workaround is no longer necessary, you can directly access private fields and methods from the console:

To better facilitate debugging, DevTools now supports evaluating expressions with private class members. (1381806)

Bergi
  • 630,263
  • 148
  • 957
  • 1,375