You can manually set the array mutator methods:
var mutatorMethods = ['fill', 'pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'];
function preventMutation() {
throw new TypeError('Array is immutable');
}
function makeImmutableArray(origArray) {
mutatorMethods.forEach(function(method) {
origArray[method] = preventMutation;
});
return origArray;
}
var foo = makeImmutableArray(['foo', 'bar', 'baz']);
See this jsbin for an example: http://jsbin.com/zeser/1/edit
This, however, only glazes the bigger problem (given that you can still modify the array using direct indexing foo[0] = 'froboz';): why do you need an immutable array?
, ? , , , . , .
, , . . (IMHO) . , if/else.
, Array .
source
share