2

Normally when you extend it options with defaultOptions you create a new object, but I would like to re-use the options object. See below code.

I basically want to do the following:

var defaultOptions = {'width': '10px', 'size': '10px'};

var options = {'width': '300px', 'name': 'sam'};

// I want to re-use the same options variable as target for extend
var optionsAfterExtend = $.extend(options, defaultOptions, options);

// should return true
alert(options.width == '300px');
alert(optionsAfterExtend == '300px');
alert(options.size == '10px');
alert(optionsAfterExtend == options);

// Because I may add extra info to the options object which the client using my plugin can use / re-use
optionsAfterExtend.data = 'sam';

// So now optionsAfterExtend.data and options.data should both equal 'sam'

Tried searching for a long time and read the jquery extend documentation, but couldn't find a proper way to do it. Is it just stupid that I want this? Even if so I'm still curious how to do it in a nice way.

4
  • If you do optionsAfterExtend.data = 'sam'; there is no way that optionsAfterExtend.data == optionsAfterExtend will return true, because your checking if the value of a property is the same as the object itself. Commented Mar 19, 2013 at 13:51
  • Updating the question, thats incorrect wording of my question. I will also try to make the question clearer. Sorry for the confusion Commented Mar 19, 2013 at 13:52
  • Are you asking how to update options every time optionsAfterExtend is changed? Commented Mar 19, 2013 at 13:56
  • Yea kind of, I would like to have options and optionsAfterExtend to point to the same object, so basically instead of creating a new object, I would like to have the extend merge the properties back into the orignal options object. Commented Mar 19, 2013 at 13:58

1 Answer 1

3

The extend method copied all properties into the object that you send in as the first parameter. To create a new object that is a combination of the others, supply an empty object as the first parameter:

var optionsAfterExtend = $.extend({}, defaultOptions, options);

If you also want the options object to change, and the objects to be the same, make a new object and then extend it back to options:

var o = $.extend({}, defaultOptions, options);
var optionsAfterExtend = $.extend(options, o);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.