Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 495
nocksock Avatar asked Nov 08 '10 11:11

nocksock


People also ask

What does this do in code?

this, self, and Me are keywords used in some computer programming languages to refer to the object, class, or other entity of which the currently running code is a part. The entity referred to by these keywords thus depends on the execution context (such as which object is having its method called).

What does a line of code do?

A line of code in assembly language is typically turned into one machine instruction. In a high-level language such as C++ or Java, one line of code generates a series of assembly language instructions, which results in multiple machine instructions.

What does this line of code do i ++?

i++ increment the variable i by 1. It is the equivalent to i = i + 1. i– decrements (decreases) the variable i by 1.


2 Answers

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)
like image 73
T.J. Crowder Avatar answered Nov 06 '22 10:11

T.J. Crowder


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)
like image 28
Nick Craver Avatar answered Nov 06 '22 11:11

Nick Craver