🍦 JavaScript
Private Properties

Updated at 2013-04-28 12:21

You can define private properties in JavaScript constructors. Note that you cannot access these in any way that I know of, thus you cannot extend the functionality. This means that the pattern is good for prototypes and small components but not usable for frameworks, plugins or modules.

function Ninja() {

  // Private properties, cannot be accessed outside.
  var _slices = 0;

  // Public getter for private property.
  this.getSlices = function() {
    return _slices;

  // Public setter for private property.
  this.slice = function() {


var ninja = new Ninja();
  ninja._slices === undefined,
  'Private data is inaccessible to us.'
  ninja.getSlices() === 1,
  'We are able to access the internal slice data with accessor function.'