Defining read-only properties in JavaScript

前端 未结 5 807
广开言路
广开言路 2020-11-28 06:23

Given an object obj, I would like to define a read-only property \'prop\' and set its value to val. Is this the proper way to do that?

5条回答
  •  执笔经年
    2020-11-28 06:51

    You could instead use the writable property of the property descriptor, which prevents the need for a get accessor:

    var obj = {};
    Object.defineProperty(obj, "prop", {
        value: "test",
        writable: false
    });
    

    As mentioned in the comments, the writable option defaults to false so you can omit it in this case:

    Object.defineProperty(obj, "prop", {
        value: "test"
    });
    

    This is ECMAScript 5 so won't work in older browsers.

提交回复
热议问题