I have observed an odd issue in jQuery's $.extend
method and referencing an array (which is considered an Object in JavaScript).
I use a defaults object, defined as follows:
var defaults = {
numbers: []
};
I have a config option I then pass a function, defined as follows:
var config = {
numbers: [1, 2, 3]
};
Within a function, I extend these two (using a deep $.extend
):
function configure(settings) {
var nums = $.extend(true, {}, defaults, settings);
nums.numbers.push(4);
console.log(settings, nums);
}
configure(config);
When I log these two, the results are as follows:
settings: {"numbers":[1,2,3]}
nums: {"numbers":[1,2,3,4]}
What I am failing to understand is, jQuery merges the objects from left to right.
I would expect that since settings is the last object that is extended, the numbers array that's created in nums
is a reference to settings.numbers
(since settings
is the last object to be $.extend
ed). This is not the case (as you can see when I log the final results).
Can somebody please explain why? It was the cause of a difficult to find bug in my app so want to ensure I understand it so it does not happen again.