tags:

views:

361

answers:

3

Hi,

I am trying to use the extend for the defaults,options in a plugin. But it does not work as described in documentation.

var empty = {}
var defaults = { validate: false, limit: 5, name: "foo" };
var options = { validate: true, name: "bar" };
var settings = $.extend(empty, defaults, options);

Here the settings is supposed to Merge defaults and options, without modifying the defaults.

but a alert(settings.validate) shows true..which means it has overridden...any comments

THnks Coool

+1  A: 

Your code:

var empty = {}
var defaults = { validate: false, limit: 5, name: "foo" };
var options = { validate: true, name: "bar" };
var settings = $.extend(empty, defaults, options);

... results in ...

settings == { validate: true, limit: 5, name: "bar" }
empty    == { validate: true, limit: 5, name: "bar" }

which is exactly what the documentation says it should do:

jQuery.extend( [deep], target, object1, [objectN] )

Extend one object with one or more others, returning the modified object.

It modifies the variable empty and returns a reference to that same variable, which you store in settings.

Noah Medling
A: 

There is something wrong though if you take it a little further :

var empty = {};
var defaults = { validate: false, limit: 5, name: "foo", buttons : {}};
var options = { validate: true, name: "bar"};
var settings = $.extend(empty, defaults, options);

settings.buttons['Ok']  = 
    function()
    {
     alert( "TEST");
    };

After this code runs defaults.buttons contains ["Ok"] can anyone explain why?

GazNewt
A: 

Hmmm... and if you write var settings = $.extend(empty, options, defaults);? I think you will have setting with full set of options+defaults props. Where dafaults will overwrite options with same name. Is it what you want?

BTW defaults means defaults. This way you can stop making mandatory params. And thats why setting have to have defaults overwitten with settings. Isn't it? And thats why you sample is correct and mine is strange ;) But answers your question (i hope).

NilColor