Kgn-web
Kgn-web

Reputation: 7555

jQuery Plugin Syntax/ JavaScript Syntax?

I came across this syntaxt many times, in JavaScript or jQuery plugin

$.fn.testPlugin = function( options ) {  

    // Create some defaults, extending them with any options that were provided
    var settings = $.extend( {
      'location'         : 'top',
      'background-color' : 'blue'
    }, options);

I do understand that the function is extended but what after $.extend({}) is not clear to me.

Upvotes: 1

Views: 69

Answers (2)

Alnitak
Alnitak

Reputation: 339786

The $.extend() method will merge any key/value pairs given in objects in the the second (and subsequent) parameter into the object passed in the first parameter. It then returns the (updated) first parameter as its result.

Hence this is just a way of specifying some default values for those two options, which will be overridden by any that the plugin user passes in the options parameter to the plugin.

For example, if you called:

$(el).testPlugin({ location: 'left' });

then within the plugin the resulting settings will be:

var settings = {
    location:         'left',
    background-color: 'blue'
};

Upvotes: 2

Dor Cohen
Dor Cohen

Reputation: 17080

jQuery.extend() is syntax for merging the contents of two or more objects together into the first object. http://api.jquery.com/jQuery.extend/

Upvotes: 0

Related Questions