Object.freeze()将按照您的要求执行(在正确实现规范的浏览器上)。TypeError
在严格模式下,修改数组的尝试要么静默失败,要么抛出。
最简单的解决方案是返回一个新的冻结副本(冻结是破坏性的):
return Object.freeze(_arr.slice());
但是,如果预期读多于写,则延迟缓存最近访问的冻结副本并在写时清除(因为addArrValue
控制写)
使用修改后的原始示例延迟缓存只读副本:
"use strict";
const mutable = [];
let cache;
function ClassName () {
const props = {};
// ... other properties ...
props.arr = {
enumerable: true,
get: function () {
return cache || (cache = Object.freeze(mutable.slice());
}
};
Object.defineProperties(this, props);
Object.seal(this);
};
ClassName.prototype.addArrValue = function addArrValue(value) {
// ... some code here to validate `value` ...
mutable.push(value);
cache = undefined;
}
使用 ES2015 类的惰性缓存只读副本:
class ClassName {
constructor() {
this.mutable = [];
this.cache = undefined;
Object.seal(this);
}
get arr() {
return this.cache || (this.cache = Object.freeze(this.mutable.slice());
}
function addArrValue(value) {
this.mutable.push(value);
this.cache = undefined;
}
}
一个“透明的”可重复使用的类hack(很少需要):
class ReadOnlyArray extends Array {
constructor(mutable) {
// `this` is now a frozen mutable.slice() and NOT a ReadOnlyArray
return Object.freeze(mutable.slice());
}
}
const array1 = ['a', 'b', 'c'];
const array2 = new ReadOnlyArray(array1);
console.log(array1); // Array ["a", "b", "c"]
console.log(array2); // Array ["a", "b", "c"]
array1.push("d");
console.log(array1); // Array ["a", "b", "c", "d"]
console.log(array2); // Array ["a", "b", "c"]
//array2.push("e"); // throws
console.log(array2.constructor.name); // "Array"
console.log(Array.isArray(array2)); // true
console.log(array2 instanceof Array); // true
console.log(array2 instanceof ReadOnlyArray); // false
一个适当的可重用类:
class ReadOnlyArray extends Array {
constructor(mutable) {
super(0);
this.push(...mutable);
Object.freeze(this);
}
static get [Symbol.species]() { return Array; }
}
const array1 = ['a', 'b', 'c'];
const array2 = new ReadOnlyArray(array1);
console.log(array1); // Array ["a", "b", "c"]
console.log(array2); // Array ["a", "b", "c"]
array1.push("d");
console.log(array1); // Array ["a", "b", "c", "d"]
console.log(array2); // Array ["a", "b", "c"]
//array2.push("e"); // throws
console.log(array2.constructor.name); // "ReadOnlyArray"
console.log(Array.isArray(array2)); // true
console.log(array2 instanceof Array); // true
console.log(array2 instanceof ReadOnlyArray); // true