Ajax Dan

Hi, I'm Dan, a Web Developer from New Zealand. I'm new to javascript and ajax, having spent most of my career developing Windows applications, and although I've liked the JavaScript code snipets that I've seen on other sites, I think there's still room for a new set of (more) integrated tools to be developed and, of course, shared with others. This blog is my attempt to help other web developers to understand and develop better object-oriented ajax tools.

Location: Griffin, Brisbane, Australia

Thursday, April 06, 2006

Object Oriented JavaScript - Part 3: Calling Base Class Functions

It's important for an object oriented language to have the ability to override a base class function. Further to this, and something few JavaScript OO developers include, is the ability to call the base class function from the function that overrides it.

The current inherits function does allow the developer to call base class functions through the this.base extension, however any changes made to primitive data types (strings, numbers and boolean data types) will not be reflected within the descendant class. A further change to the inherits function is required to overcome this deficiency.

Object.prototype.inherits = function(object) {
this.base = {_ancestor: null, _descendant: this};
if (typeof object == "object") {
this.base._ancestor = object;
else {
this.base._ancestor = new object(arguments.length > 1 ? Array.prototype.slice.call(arguments, 1) : null);
for (property in this.base._ancestor) {
if (! this[property]) {
this[property] = this.base._ancestor[property];

else if (typeof this.base._ancestor[property] == "function") {
this.base[property] = function() {
return this._ancestor[property].apply(this._descendant, arguments);


The inherits function now creates a substitute function for all methods that have been overridden. Each created function still makes a call to the overridden method, but uses the apply extension to pass the descendant object to it. This ensures that any variables updated are done within the descendant class rather than the base class.

function accumulator() {
this.sum = 0;
this.add = function(addEnd) { // Adds one number
this.sum += addEnd;
function aggregator() {
this.add = function() { // Adds many numbers
for (var i = 0; i < arguments.length; i++) {
var calculator = new aggregator();
calculator.add(5, 7, 4);
alert(calculator.sum); // Displays "16"


Post a Comment

<< Home