javascript - jquery.extend(true, [], obj) not creating a deep copy -
if deep copying worked, output "curious george" , not "ender's game". how can make deep copy? answer this question indicates $.extend(true, [], obj)
creates deep copy. yet example shows doesn't.
function person(){} person.prototype.favorite_books = []; var george = new person(); george.favorite_books = ["curious george"]; var kate = new person(); kate.favorite_books = ["the da vinci code", "harry potter"]; var people = [kate, george]; var people_copy = $.extend(true, [], people); people_copy[0].favorite_books[0] = "ender's game"; $('#text').text(people[0].favorite_books[0]);
solution
i updated jsfiddle. turns out need deep copy each object in array individually if object custom object (that is, $.isplainobject
returns false).
and here real answer:
at moment jquery can clone plain javascript objects, while you're using custom ones. , that's obvious, since jquery cannot know how instantiate new custom object. works expected:
var george = {}; george.favorite_books = ["curious george"]; var kate = {}; kate.favorite_books = ["the da vinci code", "harry potter"]; var people = [kate, george]; var people_copy = $.extend(true, [], people); console.log(people_copy[0].favorite_books == people[0].favorite_books);
reference jquery code: https://github.com/jquery/jquery/blob/master/src/core.js#l305
see checks if it's jquery.isplainobject(copy)
or it's array. otherwise performs reference copy.
Comments
Post a Comment