JavaScript privacy

The scoping function offers the only privacy in JavaScript.

So canonical:

function Ctor(dep1, dep2) { this._dep1 = dep1; this._dep2 = dep2; } Ctor.prototype.foo = function() { // use this._dep1/2... } 

... is problematic in that it does not offer encapsulation for nested dependencies.

An alternative (albeit slightly different from the location of foo ) that offers real encapsulation might be:

 function factory(dep1, dep2) { return { foo: partial(foo, dep1, dep2), // or use bind (partial could be a library fn for partial application) }; } function foo(dep1, dep2) { // use dep1/2 } 

But I rarely see this pattern. Is there a good reason not to use the latter?

+6
source share
2 answers

You have already indicated the benefits of the second template. Disadvantages:

  • you should either group methods by visibility (even if the private method is closely related to the public, but hardly related to other private methods) or repeat all the public methods in the object literal (which does not work well with jsdoc).

  • the code introduces a separate function object for each instance of your class that sacrifices some performance (usually it does not matter, but sometimes it can)

  • unlike private modifiers in many programming languages, this encapsulation cannot be avoided even if it is used incorrectly, and I really know what I am doing (historically, JavaScript was an environment where everything goes, and many attribute its success to this extensibility)

+3
source

Simple: why?

"Confidentiality" is terribly overpriced. He does not hide anything from those who really want it. The members "protected" or "private" are intended solely for the benefit of the programmer, in particular, to indicate how a particular member should be used (this is a public API, this is not so, please do not touch it if you do not know what it does). All this. A naming convention, such as the beginning of an underscore, is sufficient to implement it. If the participant’s name begins with an underscore, do not touch it unless you know what you are doing.

There is no inherent need to lean back further than that.

+3
source

All Articles