<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet href="http://ajaxcookbook.org/css/atom.xsl" type="text/xsl" media="screen"?>
<feed xmlns="http://www.w3.org/2005/Atom">
  <title type="text">Ajax Cookbook</title>
  <updated>2006-12-18T02:46:18Z</updated>
  <id>http://ajaxcookbook.org/</id>
  <icon>http://ajaxcookbook.org/favicon.ico</icon>
  <link rel="alternate" href="http://ajaxcookbook.org/" title="Ajax Cookbook" type="text/html"/>
  <link rel="self" href="http://ajaxcookbook.org/feed/" title="Ajax Cookbook" type="application/atom+xml"/>
  <entry>
    <title>Cross-Browser Event Handling and Memory Leaks</title>
    <updated>2006-12-11T05:55:27Z</updated>
    <published>2006-12-09T21:10:32Z</published>
    <id>http://ajaxcookbook.org/event-handling-memory-leaks/</id>
    <author>
      <name>Bret Taylor</name>
      <email>btaylor@gmail.com</email>
    </author>
    <link href="http://ajaxcookbook.org/event-handling-memory-leaks/" rel="alternate" title="Cross-Browser Event Handling and Memory Leaks" type="text/html"/>
    <content type="xhtml" xml:space="preserve"><div xmlns="http://www.w3.org/1999/xhtml"><p>In the &quot;old-style&quot; event registration model, you would typically register events by assigning functions to the <code>on<i>event</i></code> property of DOM elements:</p>

<pre>elem.onclick = function() {
    alert(&quot;You clicked me&quot;);
}</pre>

<p>The problem with that approach is that you can only assign a single event handler function to any given event.  All modern browsers support more advanced event registration mechanisms so you can attach multiple event listeners to any given event, though, as usual, those mechanisms vary across platforms.  This recipe can be used to register and unregister event listeners in all modern browsers:</p>

<pre>function addEventListener(instance, eventName, listener) {
    var listenerFn = listener;
    if (instance.addEventListener) {
        instance.addEventListener(eventName, listenerFn, false);
    } else if (instance.attachEvent) {
        listenerFn = function() {
            listener(window.event);
        }
        instance.attachEvent(&quot;on&quot; + eventName, listenerFn);
    } else {
        throw new Error(&quot;Event registration not supported&quot;);
    }
    return {
        instance: instance,
        name: eventName,
        listener: listenerFn
    };
}

function removeEventListener(event) {
    var instance = event.instance;
    if (instance.removeEventListener) {
        instance.removeEventListener(event.name, event.listener, false);
    } else if (instance.detachEvent) {
        instance.detachEvent(&quot;on&quot; + event.name, event.listener);
    }
}</pre>

<p>The usage model for the functions above looks like this:</p>

<pre>var elem = document.getElementById("elem");
var listener = addEventListener(elem, &quot;click&quot;, function() {
    alert(&quot;You clicked me!&quot;);
});
removeEventListener(listener);</pre>

<p>While those recipes function correctly in all major browsers, Internet Explorer has a lot of <a href="http://jibbering.com/faq/faq_notes/closures.html#clMem">memory leak bugs</a> that are exacerbated by event registration.  While the details are a bit complex (subtle interactions between function closures and COM), we can augment the recipe above with a global event deregistration function that will remove memory leaks in most applications:</p>

<pre><b>var __eventListeners = [];</b>

function addEventListener(instance, eventName, listener) {
    var listenerFn = listener;
    if (instance.addEventListener) {
        instance.addEventListener(eventName, listenerFn, false);
    } else if (instance.attachEvent) {
        listenerFn = function() {
            listener(window.event);
        }
        instance.attachEvent(&quot;on&quot; + eventName, listenerFn);
    } else {
        throw new Error(&quot;Event registration not supported&quot;);
    }
    var event = {
        instance: instance,
        name: eventName,
        listener: listenerFn
    };
    <b>__eventListeners.push(event);</b>
    return event;
}

function removeEventListener(event) {
    var instance = event.instance;
    if (instance.removeEventListener) {
        instance.removeEventListener(event.name, event.listener, false);
    } else if (instance.detachEvent) {
        instance.detachEvent(&quot;on&quot; + event.name, event.listener);
    }
    <b>for (var i = 0; i &lt; __eventListeners.length; i++) {
        if (__eventListeners[i] == event) {
            __eventListeners.splice(i, 1);
            break;
        }
    }</b>
}

<b>function unregisterAllEvents() {
    while (__eventListeners.length &gt; 0) {
        removeEventListener(__eventListeners[0]);
    }
}</b></pre>

<p>The <code>unregisterAllEvents</code> function unregisters all events globally, which kills the references between the DOM objects and the listener functions, which generally prevents event registration memory leaks.  To take advantage of the function, call it in the <code>onunload</code> handler for your page:</p>

<pre>&lt;body onunload=&quot;unregisterAllEvents()&quot;&gt;</pre>

<p class="example"><a href="http://ajaxcookbook.org/examples/eventregistration.html">See a complete example</a></p></div></content>
  </entry><entry>
    <title>Canceling and Stopping Browser Events</title>
    <updated>2006-12-08T10:34:14Z</updated>
    <published>2006-12-08T10:34:14Z</published>
    <id>http://ajaxcookbook.org/canceling-and-stopping-browser-events/</id>
    <author>
      <name>Bret Taylor</name>
      <email>btaylor@gmail.com</email>
    </author>
    <link href="http://ajaxcookbook.org/canceling-and-stopping-browser-events/" rel="alternate" title="Canceling and Stopping Browser Events" type="text/html"/>
    <content type="xhtml" xml:space="preserve"><div xmlns="http://www.w3.org/1999/xhtml"><p>If your Ajax application is graphically intensive, it probably uses a lot of CSS absolute positioned elements and the CSS <code><a href="http://www.w3.org/TR/WD-positioning-970131#Z-order">z-order</a></code> attribute extensively.  The problem with overlapping elements is that events automatically <a href="http://www.quirksmode.org/js/events_order.html">bubble up</a> from foreground elements to background elements, so if you blindly capture events like <code>click</code> in background elements, you may receive them when you are not expecting them.  For example, if you have a <code>div</code> element floating above other elements, events will automatically bubble up to background elements, often leading to your application inadvertently handling the event in both the foreground <code>div</code> and the background <code>div</code>.</p>

<p>If you want to prevent events from bubbling up to background elements, you can capture the event with this recipe:</p>

<pre>function stopEvent(e) {
    if (!e) e = window.event;
    if (e.stopPropagation) {
        e.stopPropagation();
    } else {
        e.cancelBubble = true;
    }
}</pre>

<p>For example, to prevent the container of a link to receive a <code>click</code> event when the link is clicked, you would use the function above like this:</p>

<pre>var link = document.getElementById("link");
link.onclick = stopEvent;</pre>

<p>The snippet above will prevent the background of the link from receiving a click event, but how do you prevent the link itself from getting the <code>click</code> event? This recipe completely cancels an event, which, in this case, prevents the link from executing at all:</p>

<pre>function cancelEvent(e) {
    if (!e) e = window.event;
    if (e.preventDefault) {
        e.preventDefault();
    } else {
        e.returnValue = false;
    }
}</pre>

<p>If you want to both cancel the event for the link (i.e., prevent a click from executing the link) and prevent the event from bubbling to background elements, you can combine the two functions like this:</p>

<pre>var link = document.getElementById("link");
link.onclick = function(e) {
    cancelEvent(e);
    stopEvent(e);
}</pre>

<p class="example"><a href="http://ajaxcookbook.org/examples/stopevent.html">See the example</a></p></div></content>
  </entry><entry>
    <title>JavaScript Debug Log</title>
    <updated>2006-12-03T21:58:23Z</updated>
    <published>2006-12-03T23:46:31Z</published>
    <id>http://ajaxcookbook.org/javascript-debug-log/</id>
    <author>
      <name>Bret Taylor</name>
      <email>btaylor@gmail.com</email>
    </author>
    <link href="http://ajaxcookbook.org/javascript-debug-log/" rel="alternate" title="JavaScript Debug Log" type="text/html"/>
    <content type="xhtml" xml:space="preserve"><div xmlns="http://www.w3.org/1999/xhtml"><p>Even with the most advanced debugging tools, every program requires a little &quot;<code>printf</code> debugging&quot;: run your program, print out state as it executes, and visually verify that everything is working properly.  Unfortunately, there is no built in console to print debug messages to in JavaScript, forcing many JavaScript programmers to revert to calling <code>alert()</code> in their code.  <code>alert</code> is completely infeasible for a function that gets called a lot, as it halts execution until you click an OK button.  This recipe creates a simple debug log window that does not halt execution:</p>

<pre>function log(message) {
    if (!log.window_ || log.window_.closed) {
        var win = window.open(&quot;&quot;, null, &quot;width=400,height=200,&quot; +
                              &quot;scrollbars=yes,resizable=yes,status=no,&quot; +
                              &quot;location=no,menubar=no,toolbar=no&quot;);
        if (!win) return;
        var doc = win.document;
        doc.write(&quot;&lt;html&gt;&lt;head&gt;&lt;title&gt;Debug Log&lt;/title&gt;&lt;/head&gt;&quot; +
                  &quot;&lt;body&gt;&lt;/body&gt;&lt;/html&gt;&quot;);
        doc.close();
        log.window_ = win;
    }
    var logLine = log.window_.document.createElement(&quot;div&quot;);
    logLine.appendChild(log.window_.document.createTextNode(message));
    log.window_.document.body.appendChild(logLine);
}</pre>

<p>To print log messages, you just call <code>log()</code> within your code:</p>

<pre>for (var i = 0; i &lt; 10; i++) {
    log(&quot;This is log message #&quot; + i);
}</pre>

<p>When you push your code to production, you can just replace the definition of <code>log</code> with an empty function so your users will not see your debug messages.</p>

<p class="example"><a href="http://ajaxcookbook.org/examples/debuglog.html">See the example</a></p></div></content>
  </entry><entry>
    <title>Disabling the Browser Context Menu</title>
    <updated>2006-12-03T23:23:22Z</updated>
    <published>2006-12-03T23:21:51Z</published>
    <id>http://ajaxcookbook.org/disable-browser-context-menu/</id>
    <author>
      <name>Bret Taylor</name>
      <email>btaylor@gmail.com</email>
    </author>
    <link href="http://ajaxcookbook.org/disable-browser-context-menu/" rel="alternate" title="Disabling the Browser Context Menu" type="text/html"/>
    <content type="xhtml" xml:space="preserve"><div xmlns="http://www.w3.org/1999/xhtml"><p>You can disable the browser context menu for an element in your DOM with the following JavaScript recipe:</p>

<pre>function disableContextMenu(element) {
    element.oncontextmenu = function() {
        return false;
    }
}</pre>

<p>For example, to disable the context menu over a photo on your page, you could use:</p>

<pre>disableContextMenu(document.getElementById("photo"));</pre>

<p>Browsers like Firefox do not always allow web pages to disable the context menu (this option is <a href="http://www.mozilla.org/support/firefox/options#content">a setting in Firefox</a>), so this recipe will not work 100% of the time in all browsers.</p>

<p class="example"><a href="http://ajaxcookbook.org/examples/contextmenu.html">See the example</a></p></div></content>
  </entry><entry>
    <title>Currying JavaScript Functions</title>
    <updated>2006-10-05T06:43:17Z</updated>
    <published>2006-10-05T06:39:08Z</published>
    <id>http://ajaxcookbook.org/currying-javascript-functions/</id>
    <author>
      <name>Bret Taylor</name>
      <email>btaylor@gmail.com</email>
    </author>
    <link href="http://ajaxcookbook.org/currying-javascript-functions/" rel="alternate" title="Currying JavaScript Functions" type="text/html"/>
    <content type="xhtml" xml:space="preserve"><div xmlns="http://www.w3.org/1999/xhtml"><p><a href="http://en.wikipedia.org/wiki/Currying"><i>Currying</i></a> a function is the act of transforming a function that takes <i>n</i> arguments into a function that takes <i>n</i> - 1 arguments. Essentially, currying is the act of binding the first argument of a function to a specific value, creating a new function that takes the remaining arguments.  Here's a simple example:</p>

<pre>function add(x, y) {
    return x + y;
}

// produces 7
add(3, 4);

// produces a function with x bound to 3 that takes y as an argument
var add3 = curry(add, 3);

// produces 7
add3(4);</pre>

<p>In this example, we <i>curry</i> the <code>add(x, y)</code> function to produce the <code>add3(y)</code> function that always adds 3 to its only argument.  While this may seem useless initially, currying is very useful in the context of Ajax callbacks.  For example, say you want to add a constant amount 4 to a counter every time a button is clicked?  Just curry!</p>

<pre>button.onclick = curry(callback(this, addToTotal), 4);</pre>

<p>Thanks to the functional parts of JavaScript and the ability to access JavaScript function arguments as an array with the <code>arguments</code> variable, implementing the <code>curry</code> function is easy, as this recipe illustrates:</p>

<pre>function curry(method) {
    var curried = [];
    for (var i = 1; i &lt; arguments.length; i++) {
        curried.push(arguments[i]);
    }
    return function() {
        var args = [];
        for (var i = 0; i &lt; curried.length; i++) {
            args.push(curried[i]);
        }
        for (var i = 0; i &lt; arguments.length; i++) {
            args.push(arguments[i]);
        }
        return method.apply(null, args);
    }
}</pre>

<p>This <code>curry</code> function is more flexible than the formal definition of the term: you can bind as many arguments as you want when you call <code>curry</code>, like this example, where we bind the first two arguments of a function to produce a function that only takes one argument:</p>

<pre>function add(x, y, z) {
    return x + y + z;
}

var add3 = curry(add, 2, 1); // binds x to 2 and y to 1
add3(5); // produces 8</pre>

<p class="example"><a href="http://ajaxcookbook.org/examples/curry.html">See the example</a></p></div></content>
  </entry><entry>
    <title>Transitions for Animation Effects</title>
    <updated>2006-12-18T02:46:18Z</updated>
    <published>2006-09-01T08:43:22Z</published>
    <id>http://ajaxcookbook.org/transitions-animation-effects/</id>
    <author>
      <name>Bret Taylor</name>
      <email>btaylor@gmail.com</email>
    </author>
    <link href="http://ajaxcookbook.org/transitions-animation-effects/" rel="alternate" title="Transitions for Animation Effects" type="text/html"/>
    <content type="xhtml" xml:space="preserve"><div xmlns="http://www.w3.org/1999/xhtml"><p>Doing animation with Ajax is harder than it seems.</p>

<p>The first most common mistake is to do all animation effects at a constant speed.  For many types of effects, linear/constant speed animation looks clunky because the animation starts and stops and so abruptly. The solution is to adjust the speed of the animation based on a sinusoidal curve rather than a line so that the transition looks smoother -- basically, it should start slow and end slow and speed up in the middle.</p>

<p>The second most common mistake is to do all animation at a constant frame rate.  Given the dramatic DOM performance differences between web browsers and operating systems, an animation with a constant number of frames can take an order of magnitude longer on some users' computers.  The solution is to perform animation in a constant amount of time, adjusting the frame rate based on the performance of the user's browser.</p>

<p>The <code>Transition</code> class below is a recipe that can handle any type of animation (linear, sinusoidal, etc) with a variable frame rate:</p>

<pre>function Transition(curve, milliseconds, callback) {
    this.curve_ = curve;
    this.milliseconds_ = milliseconds;
    this.callback_ = callback;
    this.start_ = new Date().getTime();
    var me = this;
    this.runCallback_ = function() {
        me.run();
    };
}

Transition.prototype.run = function() {
    if (!this.hasNext()) return;
    this.callback_(this.next());
    setTimeout(this.runCallback_, 10);
}

Transition.prototype.hasNext = function() {
    if (this.done_) return this.oneLeft_;
    var now = new Date().getTime();
    if ((now - this.start_) &gt; this.milliseconds_) {
        this.done_ = true;
        this.oneLeft_ = true;
    }
    return true;
}

Transition.prototype.next = function() {
    this.oneLeft_ = false;
    var now = new Date().getTime();
    var percentage = Math.min(1, (now - this.start_) / this.milliseconds_);
    return this.curve_(percentage);
}</pre>

<p>The <code>Transition</code> class is designed to be used with a function that defines the curve/speed of the animation.  Here are sinusoidal and linear examples:</p>

<pre>function SineCurve(percentage) {
    return (1 - Math.cos(percentage * Math.PI)) / 2;
}

function LinearCurve(percentage) {
    return percentage;
}</pre>

<p>You can use one of the functions with the <code>Transition</code> class with the following pattern:</p>

<pre>var transition = new Transition(SineCurve, 1000, function(percentage) {
    // Move your element <i>percentage</i> of the way through the animation
});
transition.run();</pre>

<p>Here is a <a href="http://ajaxcookbook.org/examples/transition.html">practical example</a> that moves text diagonally across the screen at a sinuoidal speed:</p>

<pre>var element = document.getElementById(&quot;animated&quot;);
element.style.position = &quot;absolute&quot;;
element.style.left = &quot;0px&quot;;
element.style.top = &quot;0px&quot;;

var transition = new Transition(SineCurve, 1000, function(percentage) {
    var x = element.parentNode.offsetWidth - element.offsetWidth;
    var y = element.parentNode.offsetHeight - element.offsetHeight;
    element.style.left = Math.round(percentage * x) + &quot;px&quot;;
    element.style.top = Math.round(percentage * y) + &quot;px&quot;;
});
transition.run();</pre>

<p class="example"><a href="http://ajaxcookbook.org/examples/transition.html">See the example</a></p></div></content>
  </entry><entry>
    <title>Disable Text Selection</title>
    <updated>2006-07-27T06:21:33Z</updated>
    <published>2006-07-27T06:18:01Z</published>
    <id>http://ajaxcookbook.org/disable-text-selection/</id>
    <author>
      <name>Bret Taylor</name>
      <email>btaylor@gmail.com</email>
    </author>
    <link href="http://ajaxcookbook.org/disable-text-selection/" rel="alternate" title="Disable Text Selection" type="text/html"/>
    <content type="xhtml" xml:space="preserve"><div xmlns="http://www.w3.org/1999/xhtml"><p>By default, web browsers display a text selection cursor over every visible text node in the HTML DOM, and users can select, copy, and paste any text on a web page.  This is not appropriate for many Ajax applications, particularly if they involve drag-and-drop functionality that interferes with the web browser's normal text selection facilities. This simple function disables text selection within a DOM node in all modern browsers:</p>

<pre>function disableSelection(element) {
    element.onselectstart = function() {
        return false;
    };
    element.unselectable = &quot;on&quot;;
    element.style.MozUserSelect = &quot;none&quot;;
    element.style.cursor = &quot;default&quot;;
}</pre>

<p>You can't disable text selection with CSS alone, unfortunately, because returning <code>false</code> from the <code>onselectstart</code> event is necessary to disable selection in Internet Explorer.  Changing the cursor to <code>&quot;default&quot;</code> is not necessary to disable selection, but, without it, browsers will still display the text selection cursor over the unselectable text, which is confusing to end users.</p>

<p>Example usage:</p>

<pre>disableSelection(document.getElementById(&quot;text&quot;));</pre>

<p class="example"><a href="http://ajaxcookbook.org/examples/selection.html">See the example</a></p></div></content>
  </entry><entry>
    <title>Namespace-Friendly JavaScript APIs</title>
    <updated>2006-12-03T22:56:20Z</updated>
    <published>2006-07-27T06:01:17Z</published>
    <id>http://ajaxcookbook.org/javascript-api-namespaces/</id>
    <author>
      <name>Bret Taylor</name>
      <email>btaylor@gmail.com</email>
    </author>
    <link href="http://ajaxcookbook.org/javascript-api-namespaces/" rel="alternate" title="Namespace-Friendly JavaScript APIs" type="text/html"/>
    <content type="xhtml" xml:space="preserve"><div xmlns="http://www.w3.org/1999/xhtml"><p>JavaScript has no support for packages or modules, so namespace conflicts are rampant.  In particular, as JavaScript obfuscators become prevalent, a lot of JavaScript libraries have started to look like this (an actual snippet of the <a href="http://www.google.com/apis/maps/">Google Maps API</a> JavaScript):</p>

<pre>function Cb(a){a.remove();Gb(ab,a)}</pre>

<p>Given these obfuscators choose the shortest names possible to make the size of the JavaScript as small as possible, the likelihood of a name collision when multiple APIs are included in a page is almost 100% -- after all, there are only 26 letters in the alphabet.</p>

<p>When you make a JavaScript library, you can make it play well with others by only exporting those symbols that are a part of your API using this simple recipe.  First, concatenate all of your JavaScript source code, and surround it in a single, anonymous function:</p>

<pre><b>(function() {</b>
    var privateVariable = 3;

    function MyPublicClass() {
    }

    function MyPrivateClass() {
    }
<b>})();</b></pre>

<p>This will prevent any of your symbols from being accessible to pages that include the API.  Then, explicitly export the symbols that make up your API with this simple export function:</p>

<pre>function exportSymbol(name, symbol) {
    window[name] = symbol;
}</pre>

<p>In the case of the API above, we would add this line to the end of our anonymous function:</p>

<pre>(function() {
    var privateVariable = 3;

    function MyPublicClass() {
    }

    function MyPrivateClass() {
    }

    <b>exportSymbol(&quot;MyPublicClass&quot;, MyPublicClass);</b>
})();</pre>

<p>Now, <code>MyPublicClass</code> will be accessible, but the other two symbols defined are "private" and will not interfere with the other libraries included by your API clients.</p>

<p class="example"><a href="http://ajaxcookbook.org/examples/export.html">See the complete example</a></p></div></content>
  </entry><entry>
    <title>Object-Oriented JavaScript Event Handlers</title>
    <updated>2006-12-03T22:58:24Z</updated>
    <published>2006-07-26T22:48:10Z</published>
    <id>http://ajaxcookbook.org/javascript-callbacks/</id>
    <author>
      <name>Bret Taylor</name>
      <email>btaylor@gmail.com</email>
    </author>
    <link href="http://ajaxcookbook.org/javascript-callbacks/" rel="alternate" title="Object-Oriented JavaScript Event Handlers" type="text/html"/>
    <content type="xhtml" xml:space="preserve"><div xmlns="http://www.w3.org/1999/xhtml"><p>Event-handling in JavaScript is generally done with function closures and function callbacks:</p>

<pre>function handleClick() {
    alert(&quot;You clicked the button!&quot;);
}
var button = document.getElementById(&quot;button&quot;);
button.onclick = handleClick;</pre>

<p>In object-oriented JavaScript programs, you often want to bind events to methods on an object instance rather than a global function. This recipe for <code>callback</code> demonstrates an easy way to accomplish that:</p>

<pre>function callback(instance, method) {
    return function() {
        method.apply(instance, arguments);
    }
}</pre>

<p><code>callback</code> takes the object instance as the first argument and the function/method you want to call on that object as the second argument. It takes advantage of the <code><a href="http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Objects:Function:apply">apply</a></code> method to pass arguments from the event handling function to the callback method. Example usage:</p>

<pre>function Adder() {
    this.value = 0;
}

Adder.prototype.addOne = function() {
    this.value++;
}

var adder = new Adder();
var button = document.getElementById(&quot;button&quot;);
button.onclick = <b>callback(adder, adder.addOne);</b></pre>

<p class="example"><a href="http://ajaxcookbook.org/examples/callback.html">See the example</a></p></div></content>
  </entry><entry>
    <title>Inheritance in JavaScript with Constructor Arguments</title>
    <updated>2006-12-18T02:43:18Z</updated>
    <published>2006-07-26T22:42:47Z</published>
    <id>http://ajaxcookbook.org/javascript-inheritance/</id>
    <author>
      <name>Bret Taylor</name>
      <email>btaylor@gmail.com</email>
    </author>
    <link href="http://ajaxcookbook.org/javascript-inheritance/" rel="alternate" title="Inheritance in JavaScript with Constructor Arguments" type="text/html"/>
    <content type="xhtml" xml:space="preserve"><div xmlns="http://www.w3.org/1999/xhtml"><p>JavaScript is not an <i>class</i>-based object-oriented programming language, but a <i>prototype</i>-based object-oriented language.  There are a number of subtle and not-so-subtle differences between the two models that lead to a number of programming consequences.  If you are unfamiliar with JavaScript prototypes, check out <a href="http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Guide:Details_of_the_Object_Model">this nice discussion of the JavaScript object model</a> in the Mozilla developer documentation.</p>

<p>Many JavaScript APIs, like the <a href="http://www.google.com/apis/maps/">Google Maps API</a>, expose a classical object hierachy using JavaScript prototypes.  In JavaScript, object inheritance is acheived by <i>copying</i> the prototype of the superclass to the subclass, as described in the article above:</p>

<pre>function Superclass() {
    this.x = 0;
}

Superclass.prototype.add = function(amount) {
    this.x += amount;
}

function Subclass() {
}
Subclass.prototype = new Superclass();</pre>

<p>But what happens when the constructor of a superclass takes arguments?  For example, say we defined <code>Superclass</code> above like this:</p>

<pre>function Superclass(initialValue) {
    this.x = initialValue;
}</pre>

<p>How do we subclass <code>Superclass</code> now? What arguments do we provide in our inheritance line?</p>

<pre>Subclass.prototype = new Superclass(<ins>???</ins>);</pre>

<p>The answer is to define an inheritance helper method like this:</p>

<pre>function inherit(subclass, superclass) {
    var c = function() {};
    c.prototype = superclass.prototype;
    subclass.prototype = new c();
}</pre>

<p>Then we would define <code>Subclass</code> like this:</p>

<pre>function Subclass(initialValue) {
    Superclass.call(this, initialValue);
}
<b>inherit(Subclass, Superclass);</b></pre>

<p><code>inherit</code> works by copying the prototype of <code>Superclass</code> independently of the <code>Superclass</code> function.  You can call the constructor of the superclass by using the <code><a href="http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Objects:Function:call">call</a></code> method, which is available for all JavaScript functions. The first argument to <code>call</code> is the object instance <code>this</code>, which ensures that <code>this</code> will refer to the correct instance in the body of <code>Superclass</code>.</p>

<p class="example"><a href="http://ajaxcookbook.org/examples/inheritance.html">See the example</a></p></div></content>
  </entry>
</feed>
