Is there any way to prevent replacement of JavaScript object properties?

后端 未结 6 1939
醉酒成梦
醉酒成梦 2020-12-16 00:21

I would like to make an object\'s structure immutable, preventing its properties from being subsequently replaced. The properties need to be readable, however. Is this possi

6条回答
  •  孤城傲影
    2020-12-16 01:13

    You can now force a single object property to be frozen instead of freezing the whole object. You can achieve this with Object.defineProperty and the parameter writable: false

    var obj = {
        "first": 1,
        "second": 2,
        "third": 3
    };
    Object.defineProperty(obj, "first", {
        writable: false,
        value: 99
    });
    

    In this example, obj.first now has its value locked to 99.

提交回复
热议问题