I was reading the jQuery documentation for plugin development and I ran across a line of code I cannot wrap my head around.
$.fn.tooltip = function( method ) {
if ( methods[method] ) {
return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof method === 'object' || ! method ) {
return methods.init.apply( this, arguments );
} else {
$.error( 'Method ' + method + ' does not exist on jQuery.tooltip' );
}
The line in question:
return methods[method].apply(this, Array.prototype.slice.call(arguments,1));
I understand that all javascript objects inherit call() and apply() and I understand the differance between these two functions. What I don’t understand is the prototype on the Array. Array objects already have a slice() so why is the prototype needed here? Since call() takes two arguments which are a ‘this’ (context) and a list of arguments I don’t understand how the above call invocation works. Can someone help me understand this line?
Thanks
The
argumentsobject inherits fromObject.prototype. It may look like an array, but it isn’t. To perform array operations on it, the following line is necessary:The previous line copies the
arguments“array”, and uses theslice(1)method on it.Array.prototype.slice(arguments, 1)is equivalent to:argumentsto a true array (by settingthisof Array.slice` to arguments).slice(1)method to return an array which does not contain the first element.(Note that the
argumentsobject is not modified during this process)Pseudo-code: