如何使用`defineProperty`创建只读数组属性?

时间:2014-03-19 19:08:09

标签: javascript arrays properties native-methods

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

在“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,如果我明确设置它,则没有任何差异。

2 个答案:

答案 0 :(得分:2)

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

:a;                 # Define label 'a'
   N;               # Append next line to pattern space
     $!ba;          # Goto 'a' unless it's the last line
s/\n//g;            # Replace all newlines with nothing
s/,"country"[^}]*// # Replace ',"country...' with nothing

这意味着在数组上调用props.arr = { enumerable: true, get: function () { return _arr.slice(); } }; 对原始.push数组没有任何影响,而_arr方法将是改变" private&#的唯一方法34; addArrValue变量。

_arr

答案 1 :(得分:2)

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