Tom B Tom B - 5 months ago 10
jQuery Question

Javascript array notation on object

I'd like to know how this works behind the scenes: https://learn.jquery.com/using-jquery-core/faq/how-do-i-pull-a-native-dom-element-from-a-jquery-object/

How does JQuery set up

foo[0]
to execute the
get
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
slice.call( 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:

myObj[0];


acts identically to

myObj.get(0);


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?

Answer

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];
    }
};

console.log(obj[0]);
console.log(obj.get(0));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>