I have a javascript object that maintains an internal array of objects. I have a method that returns the array but I need to prevent external manipulation of the array and the objects inside it.
Trying slice
to copy the array but I've noticed that the objects inside are still references to the originals while the array itself is new. I've never noticed this before, but I've confirmed it:
function test(){
// I want this to be safe from outside influence
var a = [{
val: 1
},{
val: 2
}];
return {
all: function(){
return a.slice();
}
}
}
var instance = test();
var copy = instance.all();
// This affects both "copy" and the original
copy[0].val = 'wrong';
// This clears "copy" but doesn't affect the original
copy = [];
http://jsfiddle.net/dczz7sL4/1/
I need to have a truly new copy so an outsider can't modify the array without using the API methods I've designed. I assume all I can do iterate the array and use $.extend
(or similar methods from other libs) to clone the objects individually - is there any easier/native alternative?