Skip to main content
3 of 5
added 281 characters in body
Scott Rippey
  • 15.8k
  • 5
  • 73
  • 88

Update: With ES6, there is a better way:

Long story short, you can use the new Symbol to create private fields.
https://curiosity-driven.org/private-properties-in-javascript

For all modern browsers with ES5:

Don't bother mixing Closures with Prototypes

I think you shouldn't mix closure variables with prototype methods. You should use one or the other.

Although you clearly already understand closures, private variables, and prototypal inheritance, I'd like to describe them to illustrate my point.

Use Closures for Private and Public

The simplest way to construct objects is to avoid prototypal inheritance altogether. Just define the private variables and public functions within the closure, and all public methods will have private access to the variables.

Use Prototype for Private and Public

In JavaScript, prototypal inheritance is primarily an optimization. It allows multiple instances to share prototype methods, rather than each instance having its own methods.
The drawback is that this is the only thing that's different each time a prototypal function is called.
Therefore, any private fields must be accessible through this, which means they're going to be public. So we just stick to naming conventions for _private fields.

Don't use Closures for Private and Prototype for Public

When you use a closure to create a private variable, you cannot access it from a prototypal method unless it's exposed through the this variable. Most solutions, therefore, just expose the variable by a method, which means that you're exposing it publicly one way or another.

So, which one to choose?

I think using prototypal inheritance makes the most sense, makes debugging easier, provides transparency, could improve performance, and so that's what I usually use.
Stick to conventions for _private fields and everything goes great.
And I don't understand why JS developers try SO hard to make fields truly private.

Scott Rippey
  • 15.8k
  • 5
  • 73
  • 88