3

我将以下内容作为模块的一部分(出于问题的目的简化了名称):

在“module.js”中:

var _arr;

_arr = [];

function ClassName () {
    var props = {};

    // ... other properties ...

    props.arr = {
        enumerable: true,
        get: function () {
            return _arr;
        }
    };

    Object.defineProperties(this, props); 

    Object.seal(this);
};

ClassName.prototype.addArrValue = function addArrValue(value) {

    // ... some code here to validate `value` ...

    _arr.push(value);
}

在“otherfile.js”中:

var x = new ClassName();

通过上面的实现和下面的示例代码,arr可以通过两种方式来实现添加值。

// No thank you.
x.arr.push("newValue"); // x.arr = ["newValue"];

// Yes please!
x.addArrValue("newValue"); // Only this route is desired.

有谁知道如何实现只读数组属性?

注意:writeable默认情况下为 false,如果我明确设置它,则不会观察到差异。

4

2 回答 2

6

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
于 2018-08-21T22:33:15.087 回答
2

回顾这一点,2 年后,一个可能的解决方案是通过属性访问器返回数组的副本。是否是最好的方法取决于各种因素(例如预期的数组大小等)

props.arr = {
   enumerable: true,
    get: function () {
        return _arr.slice();
    }
};

这意味着调用.push数组不会对原始_arr数组产生影响,并且该addArrValue方法将是改变“私有”_arr变量的唯一方法。

var x = new ClassName();

x.arr.push("newValue"); // Silently fails as it mutates a copy of _arr

console.log(x.arr); // []

x.addArrValue("hi");

console.log(x.arr); // ["hi"];
于 2016-11-01T13:04:19.730 回答