0

I've been reading Javascript Patterns by Stefanov recently. And I found this example confusing to me here:

Another case of using a convention to mimic functionality is the private members >con- vention. Although you can implement true privacy in JavaScript, sometimes >evelopers find it easier to just use an underscore prefix to denote a private >method or property. Consider the following example:

var person = {

getName: function () {

return this._getFirst() + ' ' + this._getLast(); },

_getFirst: function () {

// ... },

_getLast: function () {

// ... }

};

In this example getName() is meant to be a public method, part of the stable API,

whereas _getFirst() and _getLast() are meant to be private.

As I understand it, either a method is private or public is defined by the way it was written. For example, if we are talking about a constructor function, then, "this.getFirst() = function(){ ... } " would be a public method where as "var getFirst=function(){...}" would be private.

The example in the book is not a constructor function, tho. And I do believe one can't simply use an underscore to make a method public or private. How, then, shall we make private or public method in an object declared in the way as the example above?

Many thanks!

Community
  • 1
  • 1

2 Answers2

1

Javascript doesn't have really private variables / methods. The pattern (underscoring) is just coding convention. See MDN: Private properties. It reads

The above technique (underscoring) is simple and clearly expresses intent. However, the use of an underscore prefix is just a coding convention and is not enforced by the language: there is nothing to prevent a user from directly accessing a property that is supposed to be private.

Meanwhile, you cannot use var getFirst=function(){...} inside Object literal {...} construction.

Alex Kudryashev
  • 9,120
  • 3
  • 27
  • 36
0

It looks like it's trying to say that getName(); is an accessor within the same class as the private data member functions.