Private properties in JavaScript

JavaScript lacks of the classical OO keywords like public, protected and private, so a developer is forced to use scope in order to implement something that mimics the basic behavior of such keywords. For example, a good way to implement private members in a JavaScript class (although in JavaScript there are only functions, not classes in the strict sense of the term) is the following:

function MyClass {
  var url = location.href;
  var title = document.title;
  var ua = navigator.userAgent;

  this.setPermanentLink = function() {
    $('<p class="permalink"></p>').html(' <a href="' + url + '">Permanent link</a>').
    appendTo('#site-info');
  };
  
  //...
}

Since the first three variables lie in the function scope, they're not accessible from outside the function/class. Perhaps I'm reinventing the wheel, but this is one of the most frequently asked questions of ever (especially among traditional OO programmers).

Leave a Reply

Note: Only a member of this blog may post a comment.