nocksock
nocksock

Reputation: 5527

What does this Code do?

i'm reading through jQuery's "Plugins/Authoring" though i already wrote a few jQuery-Plugins. Now I see that jQuery has a special way of scoping the methods and calling:

(function( $ ){

  var methods = {
    init : function( options ) { // THIS },
    show : function( ) { // IS   },
    hide : function( ) { // GOOD },
    update : function( content ) { // !!! }
  };

  $.fn.tooltip = function( method ) {

    // Method calling logic
    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' );
    }    

  };

})( jQuery );

I understand the concept of what will happen in the end… but how exactly? This part is what confuses me:

    // Method calling logic
    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 );
    }

Why Array.prototype.slide.call(argumetns, 1)? And where does the variable "arguments" come from all of the sudden? Any brief or deeper explanation is much appreciated. It is said, that this is how plugins should be written… so i'd like to know why.

Thanks!

Upvotes: 7

Views: 940

Answers (5)

T.J. Crowder
T.J. Crowder

Reputation: 1074208

arguments

arguments is a part of the JavaScript language. I was confused in exactly the way you were when I first ran into it; it's not just you. :-) It's an automatic local variable in every function, and is an array-like structure giving you all of the arguments (see Section 10.6 of the spec), e.g.:

function foo() {
    var index;

    for (index = 0; index < arguments.length; ++index) {
        alert(arguments[index]);
    }
}
foo("one", "two"); // alerts "one", then alerts "two"

When I say arguments is array-like, I mean it — it's not an Array. Its references to the arguments are live (and bidirectional). For instance:

function foo(namedArg, anotherNamedArg) {
    alert(namedArg === arguments[0]);        // alerts true, of course
    alert(anotherNamedArg === arguments[1]); // also alerts true
    namedArg = "foo";
    alert(arguments[0]);                     // alerts "foo"
    arguments[0] = "bar";
    alert(namedArg);                         // alerts "bar"
}

Note that when assigning a value to namedArg, the result is reflected in arguments[0], and vice-versa.

arguments is really cool, but only use it if you need to — some implementations speed up calling functions by not hooking it up until/unless the function actually first tries to access it, which can slow the function down (very slightly).

arguments also has property on it called callee, which is a reference to the function itself:

function foo() {
    alert(foo === arguments.callee); // alerts true
}

However, it's best to avoid using arguments.callee for several reasons. One reason is that in many implementations, it's really slow (I don't know why, but to give you an idea, the function call overhead can increase by an order of magnitude if you use arguments.callee). Another reason is that you can't use it in the new "strict" mode of ECMAScript5.

(Some implementations also had arguments.caller — shudder — but fortunately it was never widespread and is not standardized anywhere [nor likely to be].)

The slice call and apply

Regarding

return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));

What that's doing is using the Array#slice method to copy the arguments into an array (minus the first argument, which was the method to call), and then passing the resulting array into the Function#apply function on the function instance it's calling. Function#apply calls the function instance with the given this object and the arguments supplied as an array. The code's not just using arguments.slice because (again) arguments isn't really an Array and so you can't rely on it having all of the Array functions, but the specification specifically says (in Section 15.4.4.10) that you can apply the Array.prototype.slice function to anything that's array-like, and so that's what they're doing.

Function#apply and Function#call are also built-in parts of JavaScript (see Sections 15.3.4.3 and 15.3.4.4). Here are simpler examples of each:

// A function to test with
function foo(msg, suffix) {
    alert(this.prefix + ": " + msg + suffix);
}

// Calling the function without any `this` value will default `this`
// to the global object (`window` on web browsers)
foo("Hi there", "!"); // Probably alerts "undefined: Hi there!" because the
                      // global object probably doesn't have a `prefix` property

// An object to use as `this`
var obj = {
    prefix: "Test"
};

// Calling `foo` with `this` = `obj`, using `call` which accepts the arguments
// to give `foo` as discrete arguments to `call`
foo.call(obj, "Hi there", "!"); // alerts "Test: Hi there!"
      // ^----^-----------^---- Three discrete args, the first is for `this`,
      //                        the rest are the args to give `foo`

// Calling `foo` with `this` = `obj`, using `apply` which accepts the arguments
// to give `foo` as an array
foo.apply(obj, ["Hi there", "!"]); // alerts "Test: Hi there!"
            // ^---------------^---- Note that these are in an array, `apply`
            //                       takes exactly two args (`this` and the
            //                       args array to use)

Upvotes: 15

Chris Morgan
Chris Morgan

Reputation: 90742

arguments is a special JavaScript variable which means "all the arguments given to this function". It isn't quite an array, but behaves almost like one, so instead of saying arguments.slice(1) it calls Array.prototype.slice.call(arguments, 1); what it's doing it taking all except the first value in the list - for func(1, 2, 3, 4) it will be [2, 3, 4].

The end result of this is that when you call $.fn.tooltip('foo', 'bar', 'baz') it will try to call methods['foo']('bar', 'baz').

Upvotes: 1

jwueller
jwueller

Reputation: 30996

Array.prototype.slide.call(argumetns, 1) converts the arguments pseudo-array into a real array (skipping the first element).

arguments contains all arguments the function you are currently in has been called with. It is automatically provided by JavaScript. Since we need a real array (arguments cannot be manipulated, etc.), we convert it to one using this statement.

Upvotes: 1

antyrat
antyrat

Reputation: 27765

Variable arguments is defined javascript variable. It stores all arguments called in function in array. For example :

function variablesCount() {
    alert(arguments.length);
}

variablesCount(var1, var2); // alerts 2

Upvotes: 1

Nick Craver
Nick Craver

Reputation: 630379

arguments is a keyword, the arguments passed to the function. But you don't want all of them, since the first you know, it's method, so this is taking every argument past the first to use in .apply()...passing those arguments into whichever method was specified in the first method argument.

If it can't find method (meaning the first argument wasn't 'init', 'show', 'hide', or 'update', then it goes to the else portion, and passes all the arguments to the init method (the default, if you will).

For example:

  • .tooltip({ thing: value }) would call init({ thing: value }) since that's the default
  • .tooltip('show', var1, var2) would call show(var1, var2)

Upvotes: 3

Related Questions