1

当将数组定义为 ES5 样式对象的属性时,我想使其属性的值无法更改。

'use strict';

var global = Object.create(Object.prototype, {
    names: {
        value: ['Barney', 'Trogdor'],
        writable: false
    }
});

global.names.push('Jackson'); // I expected a read-only error here

console.log(global.names[2]); // >> Jackson

global.names = ['Ooga', 'Booga']; // >> TypeError: "names" is read-only

看来我只保护了财产转让。

有什么方法可以防止类似Array.push()修改我的“不可写”数组的东西?

4

2 回答 2

3

Object.seal()似乎工作。

'use strict';

var global = Object.create(Object.prototype, {
    names: { value: Object.seal(['Barney', 'Trogdor']) }
});
global.names.push('Jackson'); // >> TypeError: global.names.push(...) is not extensible

编辑:其实,没关系。

在前面的示例中,我是否要附加以下代码行:

global.names[0] = 'Jackson'; // Still works

我相信Object.freeze()这是我真正想要的。

var global = Object.create(Object.prototype, {
    names: { value: Object.freeze(['Barney', 'Trogdor']) }
});
global.names.push('Jackson');  // >> TypeError: global.names.push(...) is not extensible
global.names[0] = 'Jackson';   // >> TypeError: 0 is read-only
global.names = ['Jackson'];    // >> TypeError: "names" is read-only
于 2013-12-08T09:36:56.517 回答
-2

Once all the data is loaded, why not overwrite the push method on what you have:

global.names.push = function () {return false}
于 2013-12-08T09:25:21.920 回答