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.

Name:
Location: Griffin, Brisbane, Australia

Saturday, April 01, 2006

Object Oriented JavaScript - Part 1: Inheritance

Having come from a significant background in Windows development, programming in objects is what I'm used to. Now using Javascript, I've had to code my own object oriented functionality.

Javascript doesn't have object inheritance built in, but it is possible to add this functionality to the Object class using the prototype extension.

Object.prototype.inherits = function(object) {
this.base = new object;
for (property in this.base) {
if (! this[property]) {
this[property] = this.base[property];
}
}
}

Base class functions defined in the constructor would have been copied if I had simply added object.call(this), however this would not have copied any functions defined through the prototype class. Copying each property from an instantiated class ensures that all functions (and public variables) are available within the descendant class (if they aren't already defined).

By attaching the inherits function to the Object class, it automatically becomes available to any objects that you create.

function ObjectA() {
this.whoAmI = function() {
return "I am " + this.constructor.toString().match(/function\s*(\w+)/)[1];
}
}

function ObjectB() {
this.inherits(ObjectA);
}

var myObject = new ObjectB();

alert(myObject.whoAmI()); // Displays "I am ObjectB"

Next: Passing Constructor Arguments
Then: Calling Base Class Functions

0 Comments:

Post a Comment

<< Home