jsFiddle here.
If deep copying worked, the output would be "Curious George" and not "Ender's Game". How can I make a deep copy? An answer to this question indicates that $.extend(true, [], obj)
creates a deep copy. Yet my example shows that it 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 the jsFiddle. It turns out I need to deep copy each object in the array individually if the object is a custom object (that is, $.isPlainObject
returns false).
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…