2

I wrote a simple code:

const secure = new class {
    #privateProperty = 4;
    #privateMethod() {
        console.log( 'The property ' + this.#privateProperty + ' should not be accessible outside this class' );
    }
}

If it is immediately followed by the syntax below

secure.#privateMethod();

I get an error which says Uncaught SyntaxError: Private field '#privateMethod' must be declared in an enclosing class

However, If I don't immediately call the secure.#privateMethod() and then go to developer tool - console and write the syntax there, it outputs:

The property 4 should not be accessible outside this class

Is there a special reason why this is happening?

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Uchenna Ajah
  • 320
  • 3
  • 15
  • That's because you're accessing the private method within the class – Muhammad Ovi Mar 24 '23 at 18:41
  • What developer tools are you using? Chrome devtools? VSCode debugger? – kelsny Mar 24 '23 at 18:50
  • I am using Chrome Dev Tool. – Uchenna Ajah Mar 24 '23 at 18:57
  • Why wouldn't a debugger allow invoking private methods? – Bergi Mar 24 '23 at 19:24
  • @Bergi - I was assuming some cases where a private method is required to be called only once and invoking those private method on debugger will make it call twice or more. I tested the above code as well on Firefox v111.0 and it gave an error in the debugger. But chrome and Edge doesn't give error – Uchenna Ajah Mar 24 '23 at 21:44
  • @Bergi - I believe a debugger should not invoke private method because (1): It is `private` and accessing it outside it's class defies the purpose of it's privacy. (2): Private method are most times used to run code that a developer does not want others to access probably to avoid displaying some (non-sensitive) information, but debugger will display it. There are many more reasons but this comment section allows limited character to type... – Uchenna Ajah Mar 24 '23 at 21:52
  • 1
    It's a debugger. It can do anything it wants to your code - rewrite it, skip it, make it public. Of course it will display private fields, how would the developer be supposed to debug them otherwise? – Bergi Mar 24 '23 at 23:44

1 Answers1

2

It's a feature, not a bug! New in the devtools of Chrome 111:

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

This is very useful when developing classes with private fields. You no longer need to put a breakpoint in a class method to be able to run code that accesses (gets, sets, invokes) private fields.

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