Simulating array-like methods

from jquery ninja book

by dandoyon

HTML

<ul id="results"></ul>

<span id="first"/>
<span id="second"/>

CSS

#results li.pass { color: green; }
#results li.fail { color: red; }

JavaScript

function assert(value, desc) {
    var li = document.createElement("li");
    li.className = value ? "pass" : "fail";
    li.appendChild(document.createTextNode(desc));
    document.getElementById("results").appendChild(li);
}

var elems = {
    length: 0,
    add: function(elem) {
        Array.prototype.push.call(this, elem); // Array gets faked to update the this.length
    },
    find: function(id) {
        this.add(document.getElementById(id));
    }
};
elems.find("first");
assert(elems.length == 1 && elems[0].nodeType, "Verify that we have an element in our stash");
elems.find("second");
assert(elems.length == 2 && elems[1].nodeType, "Verify the other insertion");


/*

The we define a method to add an element to the end of our simulated array, calling this
method simply add(). Rather than writing our own code, we’ve decided to leverage a
native object method of JavaScript arrays: Array.prototype.push. Normally, this
method would operate on its context array, but here we are tricking the method to use our
object as its context by using the call() method, and forcing our object to be the context
of the push() method, which increments the length property (thinking that it’s the
length property of an array), and adds a numbered property to the object referencing
passed element.

*/