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

Ash*_*rke 3 javascript arrays native-methods properties

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

在“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);
}
Run Code Online (Sandbox Code Playgroud)

在“otherfile.js”中:

var x = new ClassName();
Run Code Online (Sandbox Code Playgroud)

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

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

// Yes please!
x.addArrValue("newValue"); // Only this route is desired.
Run Code Online (Sandbox Code Playgroud)

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

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

Gra*_*ted 6

Object.freeze()将执行您的要求(在正确实现规范的浏览器上)。尝试修改数组将TypeError在严格模式下静默失败或抛出。

最简单的解决方案是返回一个新的冻结副本(冻结是破坏性的):

return Object.freeze(_arr.slice());
Run Code Online (Sandbox Code Playgroud)

但是,如果预期读取多于写入,则延迟缓存最近访问的冻结副本并在写入时清除(因为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;
}
Run Code Online (Sandbox Code Playgroud)

使用 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

“透明”的可重用类黑客(很少需要):

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
Run Code Online (Sandbox Code Playgroud)

一个适当的可重用类:

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
Run Code Online (Sandbox Code Playgroud)