O'Reilly logo

Prototype and Scriptaculous: Taking the Pain out of JavaScript by Chris Angus

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

3.3. Extensions to Core JavaScript Objects

Prototype also extends the following core JavaScript objects:

  • Document

  • Function

  • String

  • Array

  • Number

  • Event

3.3.1. Extensions to document

Document is extended to support finding elements via their CSS class. This is implemented by the method: getElementsByClassName(id[,parent])

which returns all elements of a certain CSS class. It takes an additional optional element (or id) parameter that limits the search to within that element.

3.3.2. Extensions to function

Functions are extended to better support binding an event handler onto the method of a particular object instance. Consider the counting class from earlier:

function Count()
{
       this.count=0;
}
Count.prototype.add = function() { this.count++;}
Var myCount = new Count();

We discussed earlier the fact that if we directly mapped an event handler onto myCount.add via:

element.onClick = myCount.add

it would not run on the correct instance. At the time, we solved this by adding an anonymous function:

element.onClick = function() {myCount.add();}

Prototype, however, extends Function to support this via the bind method call.

Using the bind method, we may instead write:

element.onClick = myCount.add.bind(myCount);

and avoid having to explicitly create anonymous functions.

Additionally, Function also contains a bindAsEventListener function, which does a similar job to bind, but instead is applied to functions that take events.

Using bindAsEventListener allows us to write cross-browser ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required