Tom B Tom B - 3 months ago 7x
jQuery Question

Javascript array notation on object

I'd like to know how this works behind the scenes:

How does JQuery set up

to execute the
function. I had a look at the source code but all I found was this:

get: function( num ) {
return num != null ?

// Return just the one element from the set
( num < 0 ? this[ num + this.length ] : this[ num ] ) :

// Return all the elements in a clean array this );

How can I my own object so that accessing an array index calls a function like this?

I'd like to do the same thing:


acts identically to


Looking a JQuery this must be possible as it doesn't just set
this[0] = 'whatever'
for each index manually, it executes the .get function somehow. Is there a way to say whenever an array lookup is made, to execute a function?


It's because in jQuery 0 is the key of the property in the object which holds the DOMElement. This means that you're actually accessing an object by key, not an array by index. The get() method is just a wrapper for that accessor. Here's a working example:

var obj = {
    '0': 'hello!',
    get: function(key) {
    	return this[key];

<script src=""></script>