0% found this document useful (0 votes)
18 views4 pages

Isgn 890

This document discusses creating reusable code in JavaScript. It begins by explaining the importance of standardizing object-oriented code when working with other programmers. It then describes prototypal inheritance in JavaScript, which uses prototypes to inherit properties rather than classes. Several methods for simulating classical inheritance in JavaScript are presented, including Douglas Crockford's functions for inheriting a single function, inheriting from a single parent, and inheriting individual methods from multiple parents.

Uploaded by

cejijit238
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views4 pages

Isgn 890

This document discusses creating reusable code in JavaScript. It begins by explaining the importance of standardizing object-oriented code when working with other programmers. It then describes prototypal inheritance in JavaScript, which uses prototypes to inherit properties rather than classes. Several methods for simulating classical inheritance in JavaScript are presented, including Douglas Crockford's functions for inheriting a single function, inheriting from a single parent, and inheriting individual methods from multiple parents.

Uploaded by

cejijit238
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

7273ch03final.

qxd 11/16/06 8:21 AM Page 39

CHAPTER 3
■■■

Creating Reusable Code

W hen developing code with other programmers, which is standard for most corporate or
team projects, it becomes fundamentally important to maintain good authoring practices in
order to maintain your sanity. As JavaScript has begun to come into its own in recent years,
the amount of JavaScript code developed by professional programmers has increased dra-
matically. This shift in the perception and use of JavaScript has resulted in important
advances in the development practices surrounding it.
In this chapter, we’re going to look at a number of ways in which you can clean up your
code, organize it better, and improve the quality so that others can use it.

Standardizing Object-Oriented Code


The first and most important step in writing reusable code is to write the code in a way that
is standard across your entire application, object-oriented code especially. When you saw
how object-oriented JavaScript behaved in the previous chapter, you saw that the JavaScript
language is rather flexible, allowing you to simulate a number of different programming
styles.
To start with, it is important to devise a system of writing object-oriented code and
implementing object inheritance (cloning object properties into new objects) that best
suits your needs. Seemingly, however, everyone who’s ever written some object-oriented
JavaScript has built their own scheme of doing this, which can be rather confusing. In this
section, we’re going to look at how inheritance works in JavaScript followed by a look at
how a number of different, alternative helper methods work and how to use them in your
application.

Prototypal Inheritance
JavaScript uses a unique form of object creation and inheritance called prototypal inheritance.
The premise behind this method (as opposed to the classical class/object scheme that most
programmers are familiar with) is that an object constructor can inherit methods from one
other object, creating a prototype object from which all other new objects are built.
This entire process is facilitated by the prototype property (which exists as a property
of every function, and since any function can be a constructor, it’s a property of them, too).
Prototypal inheritance is designed for single, not multiple, inheritance; however, there are
ways that this can be worked around, which I’ll discuss in the next section.

39
7273ch03final.qxd 11/16/06 8:21 AM Page 40

40 CHAPTER 3 ■ CREATING REUSABLE CODE

The part that makes this form of inheritance especially tricky to grasp is that prototypes
do not inherit their properties from other prototypes or other constructors; they inherit them
from physical objects. Listing 3-1 shows some examples of how exactly the prototype property
is used for simple inheritance.

Listing 3-1. Examples of Prototypal Inheritance

// Create the constructor for a Person object


function Person( name ) {
this.name = name;
}

// Add a new method to the Person object


Person.prototype.getName = function() {
return this.name;
};

// Create a new User object constructor


function User( name, password ) {
// Notice that this does not support graceful overloading/inheritance
// e.g. being able to call the super class constructor
this.name = name;
this.password = password;
};

// The User object inherits all of the Person object's methods


User.prototype = new Person();

// We add a method of our own to the User object


User.prototype.getPassword = function() {
return this.password;
};

The most important line in the previous example is User.prototype = new Person();.
Let’s look in depth at what exactly this means. User is a reference to the function constructor
of the User object. new Person() creates a new Person object, using the Person constructor.
You set the result of this as the value of the User constructor’s prototype. This means that any-
time you do new User(), the new User object will have all the methods that the Person object
had when you did new Person().
With this particular technique in mind, let’s look at a number of different wrappers that
developers have written to make the process of inheritance in JavaScript simpler.

Classical Inheritance
Classical inheritance is the form that most developers are familiar with. You have classes
with methods that can be instantiated into objects. It’s very typical for new object-oriented
JavaScript programmers to attempt to emulate this style of program design, however few
truly figure out how to do it correctly.
7273ch03final.qxd 11/16/06 8:21 AM Page 41

CHAPTER 3 ■ CREATING REUSABLE CODE 41

Thankfully, one of the masters of JavaScript, Douglas Crockford, set it as a goal of his
to develop a simple set of methods that can be used to simulate classlike inheritance
with JavaScript, as explained on his web site at http://javascript.crockford.com/
inheritance.html.
Listing 3-2 shows three functions that he built to create a comprehensive form of classi-
cal JavaScript inheritance. Each of the functions implement a different aspect of inheritance:
inheriting a single function, inheriting everything from a single parent, and inheriting indi-
vidual methods from multiple parents.

Listing 3-2. Douglas Crockford’s Three Functions for Simulating Classical-Style Inheritance Using
JavaScript

// A simple helper that allows you to bind new functions to the


// prototype of an object
Function.prototype.method = function(name, func) {
this.prototype[name] = func;
return this;
};

// A (rather complex) function that allows you to gracefully inherit


// functions from other objects and be able to still call the 'parent'
// object's function
Function.method('inherits', function(parent) {
// Keep track of how many parent-levels deep we are
var depth = 0;

// Inherit the parent's methods


var proto = this.prototype = new parent();

// Create a new 'priveledged' function called 'uber', that when called


// executes any function that has been written over in the inheritance
this.method('uber', function uber(name) {

var func; // The function to be execute


var ret; // The return value of the function
var v = parent.prototype; // The parent's prototype

// If we're already within another 'uber' function


if (depth) {
// Go the necessary depth to find the orignal prototype
for ( var i = d; i > 0; i += 1 ) {
v = v.constructor.prototype;
}

// and get the function from that prototype


func = v[name];
7273ch03final.qxd 11/16/06 8:21 AM Page 42

42 CHAPTER 3 ■ CREATING REUSABLE CODE

// Otherwise, this is the first 'uber' call


} else {
// Get the function to execute from the prototype
func = proto[name];

// If the function was a part of this prototype


if ( func == this[name] ) {
// Go to the parent's prototype instead
func = v[name];
}
}

// Keep track of how 'deep' we are in the inheritance stack


depth += 1;

// Call the function to execute with all the arguments but the first
// (which holds the name of the function that we're executing)
ret = func.apply(this, Array.prototype.slice.apply(arguments, [1]));

// Reset the stack depth


depth -= 1;

// Return the return value of the execute function


return ret;
});

return this;
});

// A function for inheriting only a couple functions from a parent object,


// not every function using new parent()
Function.method('swiss', function(parent) {
// Go through all of the methods to inherit
for (var i = 1; i < arguments.length; i += 1) {
// The name of the method to import
var name = arguments[i];

// Import the method into this object's prototype


this.prototype[name] = parent.prototype[name];
}

return this;
});

Let’s look at what exactly these three functions provide us with and why we should use
them instead of attempting to write our own prototypal inheritance model. The premise for
the three functions is simple:

You might also like