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.
Douglas Crockford, "JavaScript's popularity is almost completely independent of its qualities as a programming language."
The Object Literal syntax is extremely powerful and expressive. Having functions as top level objects is not new, but in Javascript and the web it allows you to hitch a function to something out of scope. Which is very useful for callbacks.
I pretty much spend 90% of my time working in a product line that is part javascript framework, part javascript re-usable components and totally object oriented. I have seen the power of javascript up very close and have a lot more respect for the language now.
Added bonus is that I am exceptionally comfortable in it too as a result of having to work out complex problems, both business and softwre related, in the language.
Sometimes a working week can be summed up into a concise and simple symbol. In the case of this week it is the comma.
Javascript is exceptionally powerful for its object literal syntax and the ability to move functions into the scope of other objects. Where once I used to complain of it giving me a black lung, now I am appreciative of its features and capabilities.
We compress out javascript down into as small a file as possible. So javascript objects which are littered across multiple modules and loaded dynamically in a development environment are compressed into just a few javascript files for production.
Browsers, especially firefox, tend to be forgiving where javascript syntax is concerned. A trailing comma in an object in firefox and safari is ok. In Internet Explorer it is not. When compressing javascript down, other issues that are fine in a raw file, such as a conditional or going across multiple lines in an if conditional, cause the page to fail as the javascript cannot be compiled by the browser's javascript runtime.
At which point it becomes a pig in a poke. Especially in large software systems with numerous teams checking in code across multiple paths, modules, packages and products. This is when the work becomes laborious and syntax checked line by line by javascript lint checkers such as
jslint and
javascript lint.
This week we got an operation aborted error from IE7/IE6 in our project. The issue
according to Microsoft's support website was that the DOM was being manipulated before it had been loaded into the browser. It was an indirection. The issue was syntax. The lesson from this week was lint check for semi-colons, brackets and trailing commas ruthlessly in Javascript code that is going to be compressed.
We recently had an issue in development with Internet Explorer's
Operation Aborted error. It halts the loading of the page nicely [not] to the horror of developer's everywhere but since most development and debugging is done on Firefox courtesy of the exceptionally
useful firebug tool it often gets missed or caught at the last moment.
The Internet Explorer javascript compiler/runtime is not always accurate in its error throwing. In fact it nearly never is, and the actual error thrown is an emergent issue relating to a deeper fault. In our case the Operation Aborted was a related error that Internet Explorer had issues with. But that is the purpose of quality control and taking the development code through strict levels of testing before publishing into production.
Sitemeter seems to have skipped that step. Websites that embedded their javascript appeared one morning on IE browsers with the Operation Aborted error.
Via ReadWriteWeb:
A bug found in both the javascript and HTML widget made thousands of sites using Sitemeter inaccessible earlier today including popular blogs such as PerezHilton.com, Gizmodo, Valleywag, and Problogger. When users would visit any sites using Sitemeter, they would be presented with an error message pop-up:
Javascript is becoming the glue that enables client-side applications in browser to offer something akin to the desktop experience. Part of its appeal is that it is widely embedded in all browsers out of the box.
This also means there is a wide range of javascript runtimes that the code has to run on with all the idiosyncrasities and permutations that come with it. It can be annoying, especially in the sub-par implementations from the many versions of Internet Explorer - however - it is no excuse to get something as badly wrong as Sitemeter did.
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.
A javascript constant uses the
const identifier and is a read-only definition. Like javascript variables constants have global and local scope. Using the perennial Circle example:
const PI = 3.14159;
function Circle(radius) {
this.radius = radius;
this.circumference = function() {
return this.radius * 2 * PI;
}
}
circle = new Circle(10);
alert(circle.circumference());
There is a Math.PI constant in the javascript libraries. So this isn't necessarily a good example. A constant can be declared and used in a javascript object as a private variable and its scope will only be in the object.
function Circle(radius) {
this.radius = radius;
const PI = 3.14159;
this.circumference = function() {
return this.radius * 2 * PI;
}
this.expansion = function(by) {
return this.radius * by * 2 * PI;
}
} But what if we place a constant in global scope above a Javascript object, then try to change that constant by declaring it again in a function that is run from onload() in the body tag?
const PI = 3;
function Circle(radius) {
this.radius = radius;
this.circumference = function() {
return this.radius * 2 * PI;
}
this.expansion = function(by) {
return this.radius * by * 2 * PI;
}
}
function run() {
circle = new Circle(10);
alert(circle.expansion(2));
const PI = 3.14159;
alert(circle.expansion(2)); I deliberately used 3 as the initial PI declaration, though I think some town passed a law once that pi was equal to three, to differentiate from the 3.142 results.
The Circle picks up the PI constant as 3 despite trying to override the constant in the run() method. If we reorganise the run method to put the redeclared constant before the instantiation of the Circle the result is the same.
function run() {
const PI = 3.14159;
circle = new Circle(10);
alert(circle.expansion(2));
} The global scoping of the constant over-rides the local scoping of a constant with the same name. If PI is declared in the global scope twice there is a javascript error, "redeclaration of const".
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.
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.
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".
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

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;