[removed] final / immutable global variables?

前端 未结 14 2070
既然无缘
既然无缘 2020-12-13 09:03

I think I know the answer but... is there any way to prevent a global variable from being modified by later-executing

14条回答
  •  轮回少年
    2020-12-13 09:27

    Object.defineProperty(window, 'CONSTANT_NAME', {value: CONSTANT_VALUE});
    
    // usage
    console.log(CONSTANT_NAME);
    

    Object.defineProperty() creates a property with the following default attributes:

    • configurable true if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. Defaults to false.

    • enumerable true if and only if this property shows up during enumeration of the properties on the corresponding object. Defaults to false.

    • writable true if and only if the value associated with the property may be changed with an assignment operator. Defaults to false.

    if the "constant" is an object you might additionally want to make it immutable by freezing it. obj =Object.freeze(obj). have in mind that child-property-objects are not automatically frozen.

提交回复
热议问题