A quick exploration of Javascript's prototyping mechanism.

I

Javascript is sufficient object aware that object oriented design can be done with the language. The semantics for OO Javascript are alien to most of the current popular OO languages such as Java, C# and Python.

The main difference is the lack of a class keyword in Javascript so a class declaration is done with a function instead and the methods of the object are not bounded by the brackets {} or whitespace under the class keyword. One of the good things of the C-like languages and python's white space is that it makes for an aesthetic rigor so that encapsulation is held within a physical space in the source code, not just a compiler recognised one.

Rather than having a rats nest of nested literal functions inside an object declared with a function in Javascript the prototype property enables semantic and aesthetic appearance of encapsulation.

The prototype allows attributes and methods to be attached to an object. For instance:

 function Jot(username, description_html) {
this._username = username;
this._description_html = description_html;
}
Jot.prototype.getDescription = function() {
return this._description_html.replace('<p>','\n');
}

Which exposes the object's members username and description_html and the method which returns the description without paragraph tags.

II

Prototyping can also be used to add functionality to existing or core objects whose internal details you have no control over. This can be done without the need for subclassing the object and having to use inheritance to achieve that behavior.

Adding prototype functionality to the Date() object is a good example. A common cause of confusion between American and Australian dates is that the Month and Date are in opposite positions when dates are written in local shorthand.

For instance:

Date.prototype.getAustralianDate = function() {
  return (this.getDate() + '/'
+ this.getMonth() + '/'
+ this.getFullYear());
}
Date.prototype.getAmericanDate = function() {
return (this.getMonth() + '/'
+ this.getDate() + '/'
+ this.getFullYear());
}

And to test it:

d = new Date();
alert(d.getAustralianDate() + "\n" + d.getAmericanDate());

The alert shows the Australian style of date on the first line and the American style on the second line.

III

Does a prototype declaration over-ride a variable of the same name being set in a javascript constructor?

function Rock() {
  this.face = "mossy";
}
 
rock = new Rock(); alert(rock.face); Rock.prototype.face = "dry"; alert(rock.face); rock2 = new Rock(); alert(rock2.face);

The output is "mossy", "mossy" and "mossy". So the answer is no.

What about an alert that includes both this.face and prototype.face:

rock = new Rock();
Rock.prototype.face = "dry";
alert(rock.face + " " + Rock.prototype.face);

This returns "mossy dry". However if there is no public variable declared in the Javascript's object constructor:

function Rock() {
  this.weight = 10; // kgs
}
 
rock = new Rock(); Rock.prototype.face = "dry"; alert(rock.face);

The answer is "dry".
Exploration of private variables/methods in OOP Javascript.

Private Variables

Scoping in Javascript is either function level or global. It doesn't support block scoping. This makes using private variables in a class with the prototype style impossible. As the private variable is inside the constructor function declaration and the prototype functions cannot see it unless the private variable is made public via this. One of the benefits of Object Oriented Programming is encapsulation and the hiding of the inner workings of the business object from the public interface. One way around this limitation is to declare the objects non-literally without prototypes.

function WorkOrder () {
  this.work_complete = null;
  this.invoice_date = null;
  var invoice_state = false;

this.invoice = function(d) { if (this.work_complete != null) { if (d != null && typeof(d) != 'undefined') { this.invoice_date = d; invoice_state = true; } else { throw "Work Order cannot be invoiced with an invalid date."; } } else { throw "Work Order cannot be invoiced unless work is complete."; } }

this.is_invoiced = function() { return invoice_state; } }

The variable invoice_state is private as it is declared with var and not this. Declaring a variable with this makes it public within the object. Because the class is written without prototyping the invoice_state variable is valid within the function scoping limitation of javascript.

To test this object:

wo = new WorkOrder();
alert('Is the work order Invoiced? ' + wo.is_invoiced());
wo.work_complete = new Date();
wo.invoice(new Date());
alert('Is the work order Invoiced? ' + wo.is_invoiced());

Private Methods

Private variables and methods can be set in a Javascript object.

function Rock() {
  this.color = "brown";
  var weight = "25";
   var getRockTemperature = function () {
    return "100F";
  }
   this.getTemperature = function () {
    return getRockTemperature(); 
  }
   this.getWeight = function () {
    return weight;
  }; 
}

The weight variable and getRockTemperature() method are private as they have been declared with a var modifier. The getTemperature(), getWeight() and color variables are public as they have been declared with the this modifier. Since methods and variables are top-level in javascript a function can be set as a variable.

Object Oriented Javascript - Private Methods

Private variables and methods can be set in a Javascript object.

function Rock() {
  this.color = "brown";
  var weight = "25";
   var getRockTemperature = function () {
    return "100F";
  }
   this.getTemperature = function () {
    return getRockTemperature(); 
  }
   this.getWeight = function () {
    return weight;
  }; 
}

The weight variable and getRockTemperature() method are private as they have been declared with a var modifier. The getTemperature(), getWeight() and color variables are public as they have been declared with the this modifier. Since methods and variables are top-level in javascript a function can be set as a variable.

Object Oriented Javascript - Prototyping I

Javascript is sufficient object aware that object oriented design can be done with the language. The semantics for OO Javascript are alien to most of the current popular OO languages such as Java, C# and Python.

The main difference is the lack of a class keyword in Javascript so a class declaration is done with a function instead and the methods of the object are not bounded by the brackets {} or whitespace under the class keyword. One of the good things of the C-like languages and python's white space is that it makes for an aesthetic rigor so that encapsulation is held within a physical space in the source code, not just a compiler recognised one.

Rather than having a rats nest of nested literal functions inside an object declared with a function in Javascript the prototype property enables semantic and aesthetic appearance of encapsulation.

The prototype allows attributes and methods to be attached to an object. For instance:

 function Jot(username, description_html) {
this._username = username;
this._description_html = description_html;
}
Jot.prototype.getDescription = function() {
return this._description_html.replace('<p>','\n');
}

Which exposes the object's members username and description_html and the method which returns the description without paragraph tags.

OOP Javascript - Prototyping II

Prototyping can also be used to add functionality to existing or core objects whose internal details you have no control over. This can be done without the need for subclassing the object and having to use inheritance to achieve that behavior.

Adding prototype functionality to the Date() object is a good example. A common cause of confusion between American and Australian dates is that the Month and Date are in opposite positions when dates are written in local shorthand.

For instance:

Date.prototype.getAustralianDate = function() {
  return (this.getDate() + '/'
+ this.getMonth() + '/'
+ this.getFullYear());
}
Date.prototype.getAmericanDate = function() {
return (this.getMonth() + '/'
+ this.getDate() + '/'
+ this.getFullYear());
}

And to test it:

d = new Date();
alert(d.getAustralianDate() + "\n" + d.getAmericanDate());

The alert shows the Australian style of date on the first line and the American style on the second line.

Javascript Closures and Scoping

Because Javascript has functions as obvious top level objects it can be easy to move the scoping of variables around using closures. It is probably the power of the language as it makes callback code very, very simple to implement. The downside is that in a complex object literal the keyword 'this' can have three different scopings. From here:

Closures can be a nice tool for creating your own DSL, to make your code get closer to the design model. But closures can also take you further away from the design model, by creating constructs that only make sense in the abstract.

One of the purposes of Object Oriented Programming is to make scope consistent and opaque. Closures mess with this paradigm by moving the scope of variable into the domain of other objects. So that comment makes a good point. The problem is that closures are so useful and simplify numerous problems by their properties.

Most Popular on South Sea Republic

The articles that have been viewed the most:

Most Popular Restaurants in Phoenix

Phoenix Eats Out is the restaurant review site for Phoenix, Scottsdale and Old Town Scottsdale which lists the modernist and contemporary restaurants, taverns and bars in the greater Phoenix area. This is the list of the most popular restaurants pages from phoenixeatsout.com that have been viewed the most; My personal favourite restaurants in Phoenix are AZ88, Postinos, Bomberos with Grazie, Humble Pie, Orange Table, The Vig, Fez and others coming close behind. View the complete list with the photo-journalistic style images on phoenixeatsout.com

Most Popular Hikes in Arizona

Arizona is an outdoor state and has lots of hiking in the city and around the state. Phoenix is unusual for most cities in having several large mountains in the center of the city with great hiking. Anyone who comes to Phoenix has to do the Echo Canyon trail on Camelback and the Summit Hike on Squaw Peak or Piesta Peak. The views of the city, suburbs and surrounding mountains are wonderful from Camelback and Piesta Peak. For more experienced hikers there is the McDowell Mountains in North Scottsdale that has several difficult and strenuous hikes in Tom's Thumb and Bell Pass. Alternatively, you can hike the highest mountain in Arizona. At 12,600 feet Humphrey's Peak is a long and difficult hike.

Alternate Australian Constitutions

Between 2004 and 2009 this site, southsearepublic.org, was a constitutional blog based on scoop which focused on Australian and global constitutional issues. One of the strongest aspects of it was the development of constitutions by those involved in the blog. These constitutions are the outcome: The constitutions were built using principles from Montesquieu's separation of powers, the enlightnment's universal political rights and the ancient Athenian technology of sortition and choice by lot.

Archives For South Sea Republic

South Sea Republic started in 2004 as an Australian constitutional blog in 2004 based on scoop software. It was an immigrative outgrowth of Kuro5hin. The archives for each year since then; The articles are ordered by views.

Who Is Cam Riley

Cam Riley I am an Australian living in the United States as a permanent resident. I am a software developer by trade and mostly work in Java and jump between middleware and front end. I originally worked in the New York area of the United States in telecommunications before moving to Washington DC and working in a mix of telecommunications, energy and ITS. I started my own software company before heading out to Arizona and working with Shutterfly. Since then I have joined a startup in the Phoenix area and am thoroughly enjoying myself.

I do a lot of photography which I post on this website, but also on flickr. I have a photo-journalistic website which lists the modernist and contemporary restaurants in phoenix. I have a site on the Australian Flying Corps [AFC] which has been around since the 1990s and which I unfortunately lost the .org URL to during a life event; however, it is under the www.australianflyingcorps.com URL now. The AFC website has gone through several iterations since the 90s and the two most recent are Australian Flying Corps Archives(2004-2002) and Australian Flying Corps Archives(2002-1999) which are good places to start.

Websites Worth Reading

Websites of friends, colleagues and of interest;