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

-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 に答える