DEV Community

Discussion on: You Can Create Private Properties In JS (accessor pattern)

Collapse
 
benaryorg profile image
#benaryorg

I haven't extensively worked with JavaScript, so out of curiosity:
JavaScript is readable by anyone with access to the source code, including the user in most cases.
Why would I go through all of this?
I don't see a reason to restrict access to any property of an application, besides the obvious "Don't touch it" which I usually solve using some sort of PEP 8 naming scheme.
I can imagine that maybe there are security critical applications (think of maybe E2E encrypted messaging) that want to prevent encryption keys to be accessible by injected JavaScript, but that's about it. (EDIT: that however seems to be more of a security through obsurity kind of thing)

Am I overlooking something here?

Collapse
 
guitarino profile image
Kirill Shestakov

You're right that the source code is available to everyone and that people can just step through your code and gain access to any object or a variable they encounter. But there's still importance in making properties private as a means to distinguish between a property people can change, play around with and a property that is exposed to the public yet people shouldn't touch. Example: suppose you're creating a Class and publishing it as a library. Users of the library can use your Class to create instances that will have some properties. You might want to have some properties per each Class instance that you don't want people to mess with, in which case it makes sense to make them private. I don't think this solution can help with security though.

Collapse
 
benaryorg profile image
#benaryorg

Wouldn't a convention/readme saying "don't touch references starting with an underscore" suffice for that?
Building wrappers and doing language-magic seems a bit overkill.

Thread Thread
 
guitarino profile image
Kirill Shestakov

If it suffices for you to just mention it in Readme, good. It's probably not enough for me.

Also, the method I described doesn't require you to do wrappers. It requires you to create a closure, but you should probably have it anyway (module pattern).