Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery / javascript: jQuery.fn.reverse = [].reverse;

This little jQuery plugin:

jQuery.fn.reverse = [].reverse;

How does it work? Where is the object binding - Array prototype to reverse function? I don't really understand how it works behind the scene. Some explanation would be nice. Greetings

like image 421
Liglo App Avatar asked Apr 03 '13 07:04

Liglo App


2 Answers

[].reverse is the .reverse() function from Array prototype. jQuery is leveraging this instead of defining their own.

[] creates an empty Array and it's perfectly valid to reference the .reverse function from it.

So now, in jQuery, one can do $.reverse() if the jQuery object contains a collection of elements.

like image 136
Amy Avatar answered Oct 04 '22 15:10

Amy


jQuery.fn is an alias for jQuery.prototype.

So this plugin adds Array's reverse function to all objects created with new JQuery(), which is the case for the collections built with $.

And it works because the reverse function's specification makes it apply to any object which has a length and indexed properties . You can test it using this :

var a = {0:'a', 1:'b'};
a.length = 2;
console.log([].reverse.call(a)); // it works
like image 31
Denys Séguret Avatar answered Oct 04 '22 15:10

Denys Séguret