Jon Aquino's Mental Garden

Engineering beautiful software jon aquino labs | personal blog

Thursday, August 13, 2009

Public and Private Methods in JavaScript

At Ning, here’s how we do public and private methods in JavaScript:

/**
* A scrollable list that can display large numbers of contacts.
*
* @param contacts contact objects
*/
xp.ContactSelector = function(args) {

/** Container for public functions. */
var self = {};

/** Container for private functions. */
var _ = {};

/**
* Initializes the object.
*/
_.initialize = function() {
if (!args.contacts) {
_.installSearchbox();
}
};

/**
* Adds a searchbox to the ContactSelector.
*/
_.installSearchbox = function() {
// This is a private method
};

/**
* Returns the contacts that the user has selected
*
* @return the selected contact objects
*/
self.getSelectedContacts = function() {
// This is a public method
};

. . . . . . . . . .

_.initialize();
return self;
};


Private methods begin with _., while public methods begin with self.. There are some interesting things about this setup:
  • Public methods are accessible on the object created by this function. Private methods are not accessible.
  • Public and private methods can be defined in any order, regardless of which calls which. This is because they are properties of self and _. If they were defined as standalone functions, then order would matter.
  • You can inherit from another object by adding the following to initialize(): self = xp.AbstractContactSelector(args);


The first point is similar to Douglas Crockford’s technique described in Private Members in JavaScript.

0 Comments:

Post a Comment

<< Home