[removed] final / immutable global variables?

前端 未结 14 2088
既然无缘
既然无缘 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条回答
  •  旧时难觅i
    2020-12-13 09:22

    Instead of declaring all such variables in the global scope, you could have one global object wrapping around those variables. Using Object.defineProperty() and/or Object.defineProperties() with the writable flag set to false, you can have an immutable variable.

    var myObj = {};
    
    Object.defineProperty(myObj, 'myVar', {
        value: someValue,
        writable: false
    });
    

    Or you could just use the const keyword

    const MY_VAR = 10;
    

提交回复
热议问题