DEV Community

Discussion on: What's the best way to do encapsulation?

Collapse
 
lexlohr profile image
Alex Lohr

It is possible to have the equivalent of private fields inside a closure in plain old JavaScript. Consider the following example:

function guessMyAge(privateAge) {
  return function(guessedAge) {
    return guessedAge === privateAge
      ? 'right'
      guessedAge < privateAge
        ? 'more'
        : 'less'
  }
}

The same is also possible with prototypal inheritance. Why doesn't TypeScript use it? Because it expects its level of trust to come from the type checker. If you attempt to access a private field, it will emit a warning and fail to transpile your code. If you cannot trust the user of your TypeScript API, you need to hide your private fields yourself.

That being said, to answer your question: it depends on the use case. What is your rationale behind the encapsulation?

  • tidy API: naming convention will suffice. At least all the private stuff will be at the top of the list and can easily be filtered. If need be you can make them non-enumerable.
  • security concerns: true private fields are the way to go.

There might be some use cases in between. YMMV.