I am trying to understand lines 10 and 12 of the below code, and have given my attempt to explain. Please correct me as applicable.
//Line 10
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
//Line 12
return methods.init.apply(this, arguments);
Line 10. If the argument provided to samplePlugin is a method, then make that method have the same this
as is at the current script's location (i.e. Line 10), and ... Help! Where is arguments
defined? What is with the call()
? EDIT. Okay, it seems Array.prototype.slice.call(arguments, 1)
makes a real array out of all the arguments except the first one, however, still is a bit of a mystery.
Line 12. Else if the argument provided to samplePlugin is an object or empty, then make the init
method have the same this
as is at the current script's location (i.e. Line 12), and ... Seems simpler, but still need help...
(function($){
var methods = {
init : function (options) {return this.each(function () {/* ... */});},
method1 : function () {return this.each(function () {/* ... */});},
method2 : function () {return this.each(function () {/* ... */});}
};
$.fn.samplePlugin = function(method) {
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); //Line 10
} else if (typeof method === 'object' || ! method) {
return methods.init.apply(this, arguments); //Line 12
} else {
$.error('Method ' + method + ' does not exist on jQuery.samplePlugin');
}
};
}(jQuery)
);