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

Sunday, April 02, 2006

Object Oriented JavaScript - Part 2: Passing Constructor Arguments

The current inherits function is ideal for simple objects that don't require arguments to be passed to their constructor. In order to cater for the more complex objects that do require them, we'll need to add some new functionality.

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

In addition to passing arguments, the inherits function now also allows the developer to pass a fully instantiated object, if this is their preference.

function fruitTree(fruit) {
this.fruit = fruit;

function appleTree(variety) {
this.variety = variety;
this.toString = function() {
return this.variety + " " + this.fruit + " Tree";
this.inherits(new fruitTree("Apple"));
// Or use "this.inherits(fruitTree, "Apple");"

var myTree = new appleTree("Granny Smith");

alert(myTree); // Displays "Granny Smith Apple Tree"

You can place the inherits function anywhere within the constructor, but placing it after variable and function definitions ensures that duplicate base class variables and functions aren't needlessly copied across (and then later overwritten).

Next: Calling Base Class Functions


Post a Comment

<< Home