I recently learned about a new Javascript Feature (private instance fields) that allow you to make certain object properties or methods private when using a ES6 class. So you can't view or set them using object.property or object property = value. However if you just log the object itself to the console it will show you all the properties including the supposedly private fields.
Javascript also already blocks child classes from being able to view or edit the information. It also blocks those values from being read using Object.entries, Object.keys and Object.values. So my question is how can I report this or possibly help implement in newer versions of Javascript.
I know a lot of you might be like well you shouldn't include sensitive information inline in the browser, but why have the private class feature in the first place then.
I can personally think of situations where you may want to hide information that might be processed behind the scenes. Like perhaps you unencrypt or some sort of algorithm that takes time to process on the backend so you only want to have to run it once. However, you need the info you get back for multiple features, so you want to store it client side. At the same time though you don't want the client to be able to see that info.
Example: Information is readable in the console. EDIT: (You may have to copy and paste the snippet to a seperate js file or run it in the browser to see issue.)
Object is viewable
class Account {
#pin;
constructor(owner, pin) {
this.owner = owner;
this.#pin = pin;
}};
const acc = new Account('John Doe', 1234);
console.log(acc); //Shows you pin in object.
Property is private though
class Account {
#pin;
constructor(owner, pin) {
this.owner = owner;
this.#pin = pin;
}};
const acc = new Account('John Doe', 1234);
console.log(acc.#pin); //Won't allow you to see pin.
CodePudding user response:
Private methods and properties are Not intended for hiding sensitive data.
It is used to hide certain properties or methods from the developer who are using it. This can be useful to hide internal variable and methods to prevent overwritten or read.
See more at Encapsulation.
JavaScript, however does not have private fields. JS developers will use a leading _
conventionally to indicate a certain variable or method are for internal use only. However, it does not restrict access to it.
The new #
is an access modifier (similar to private
in java) that implements private fields at a syntax level, instead of a workaround leading _
.