Question

SlidesJS is a jQuery content-slider plugin. I am trying to understand the source. I am relatively new to Javascript and jQuery. However, what I am interested in, is this line in the source code:

$.fn.slides = function( option ) {
   // override defaults with specified option
   option = $.extend( {}, $.fn.slides.option, option );
      ...
}

I understand by the comments that the author intends to merge two arrays, one containing the default values for option and the other is the option argument passed through calling the function. However, don't they both refer to the same variable: the argument of the function slides(option)?

It seems to work anyway. What's the magic here?

Était-ce utile?

La solution

The option argument is an Object that contains corresponding setting values for the plugin. $.fn.slides.option contains the default settings for the plugin. So when you pass your custom settings (via the option parameter), these two objects are merged and your custom values overwrites the defaults.

The jQuery.extend method is the key here. It merges the contents of two or more objects together into the first object.

option = $.extend( 
              {}, // the target new Object which represents the final merged options
              $.fn.slides.option, // Object with default option values
              option // Object with custom option values (the passed argument)
         );

See documentation here.

Autres conseils

However, don't they both refer to the same variable: the argument of the function slides(option)?

The answer is no, $.fn.slides.option is a property of the $.fn.slides function, whereas option is a function parameter/argument of the $.fn.slides function.

The function parameter or argument is like a local variable only accessible within the function block, unlike properties of functions that share the same scope as the function itself.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top