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
[].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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With