Javascript:final/immutable全局变量?

jtg*_*ver 41 javascript

我想我知道答案但是......有没有办法阻止全局变量被后来执行修改<script>?我知道全局变量首先是坏的,但是在必要时,有没有办法让它"最终"或"不可变"?欢迎黑客/创意解决方案.谢谢

Rea*_*ed. 49

常量关键字?


Dan*_*yon 14

您可以使用闭合技术,MYGLOBALS是,有一个叫做的getValue反对"全局"关联数组函数是超出范围以外MYGLOBALS例如一切的对象.

var MYGLOBALS = function() {
    var globals = {
        foo : "bar",
        batz : "blah"       
    }
    return { getValue : function(s) {
            return globals[s];
        }
    }
}();
alert(MYGLOBALS.getValue("foo"));  // returns "bar"
alert(MYGLOBALS.getValue("notthere")); // returns undefined
MYGLOBALS.globals["batz"] = 'hardeehar'; // this will throw an exception as it should
Run Code Online (Sandbox Code Playgroud)

  • 不错的尝试,但无论如何,他们仍然可以在一个目标中取代MYGLOBALS. (6认同)
  • 或者用MYGLOBALS中的`getValue`属性替换另一个返回不同值的函数. (2认同)

小智 13

我知道这个问题很旧,但你可以使用Object.freeze(yourGlobalObjectHere); 我刚刚在这里写了一篇关于它的博客文章.


小智 9

是的,const在某些语言中是常​​数或最终的缩写.谷歌"javascript变量常数"或常量加倍我甚至自己测试过它

const yourVar = 'your value';
Run Code Online (Sandbox Code Playgroud)

那就是你要找的东西.


ser*_*sam 5

这将是更清洁的方法

   var CONSTANTS = function() {
        var constants = { } ; //Initialize Global Space Here
        return {
            defineConstant: function(name,value)
            {
                if(constants[name])
                {
                   throw "Redeclaration of constant Not Allowed";
                }
            },
            getValue(name)
            {
               return constants[name];
            }
        } ;
    }() ;
    CONSTANTS.defineConstant('FOO','bar') ;
    console.log(CONSTANTS.getValue('FOO')) ; //Returns bar
    CONSTANTS.defineConstant('FOO','xyz') ; // throws exception as constant already defined
    CONSTANTS.getValue('XYZ') ; //returns undefined
Run Code Online (Sandbox Code Playgroud)


dre*_*lab 5

Object.defineProperty(window, 'CONSTANT_NAME', {value: CONSTANT_VALUE});

// usage
console.log(CONSTANT_NAME);
Run Code Online (Sandbox Code Playgroud)

Object.defineProperty()创建具有以下默认属性的属性:

  • configurabletrue 当且仅当该属性描述符的类型可以更改并且该属性可以从相应的对象中删除时。 默认为 false。

  • enumerable当且仅当该属性在相应对象的属性枚举期间出现时才为 true。默认为 false。

  • writable当且仅当与属性关联的值可以通过赋值运算符更改时为 true。默认为 false。

如果“常量”是一个对象,您可能还想通过冻结它来使其不可变。obj =Object.freeze(obj)。请记住,子属性对象不会自动冻结。