#14613 closed bug (notabug)
Extended objects share single array
Reported by: | Owned by: | ||
---|---|---|---|
Priority: | undecided | Milestone: | None |
Component: | core | Version: | 1.10.2 |
Keywords: | Cc: | ||
Blocked by: | Blocking: |
Description
I am not sure if this is a bug, a lack of documentation, or a misunderstanding on my part so I apologize in advance.
When using jQuery.extend() to merge 2 objects (obj1, and obj2) into a new empty object (target), any arrays from obj2 are actually shared between instances of target. So if any instance of target modifies the array, all instances see the change.
A code example is worth a thousand words so please check the following jsfiddle: http://jsfiddle.net/WxpSj/1/
I would expect the console output for the array to say just cat? but instead it says ["chicken", "bird", "cat"].
Change History (5)
comment:1 Changed 9 years ago by
comment:2 Changed 9 years ago by
Component: | unfiled → core |
---|---|
Resolution: | → notabug |
Status: | new → closed |
comment:4 Changed 9 years ago by
Yes, I read that documentation but it does really talk about this case. It is saying (at least how I read it based on the provided example) that if you merge 2 objects both containing an array with the same name, the second one will clobber the first rather than merging it's elements with the first object's array.
The fact that "if you do not do a deep merge, the array is actually a reference and all modifications of that array's elements will be present in any other object that extends from this one" is not mentioned or implied anywhere that I can see.
So then maybe this requires documentation updates (which I believe requires another bug request)?
comment:5 Changed 9 years ago by
All assignments of objects in JavaScript use the same referenced object rather than creating a new independent copy. This seems like a misunderstanding of JavaScript arrays rather than a jQuery question. If the documentation was truly ambiguous we would have heard more about it in the past 7 years.
This is expected behavior. Use a deep merge to avoid shallow reference copies: http://jsfiddle.net/WxpSj/3/
http://api.jquery.com/jQuery.extend/: