[removed] final / immutable global variables?

前端 未结 14 2064
既然无缘
既然无缘 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:21

    what about this code by http://ejohn.org/ @ http://ejohn.org/blog/ecmascript-5-objects-and-properties/

    Look like this actually works... I run some "little" testing and freeze the variables and attributes.

    Freezing an object is the ultimate form of lock-down. Once an object has been frozen it cannot be unfrozen – nor can it be tampered in any manner. This is the best way to make sure that your objects will stay exactly as you left them, indefinitely.

    Object.freeze = function( obj ) {
      var props = Object.getOwnPropertyNames( obj );
    
      for ( var i = 0; i < props.length; i++ ) {
        var desc = Object.getOwnPropertyDescriptor( obj, props[i] );
    
        if ( "value" in desc ) {
          desc.writable = false;
        }
    
        desc.configurable = false;
        Object.defineProperty( obj, props[i], desc );
      }
    
      return Object.preventExtensions( obj );
    };
    

    Little example

    var config = (function (__name) {
        name: __name
        var _local = {
            Server: "SomeText",
            ServerDate: "SomeServerDate",
            JSDate : Util.today(),
            User : {
                user: "1stUser",
                name: "",
                email: ""
            },        
        }
    
        /*Private Methods*/
        function freezing(__array) {
            $.each(__array, function (_index, _item) {
                Object.freeze(_item);
            });
        }
    
        /*Public Methods*/
        var $r = {};
    
        $r.info = function () {
            return _local;
        }
    
        freezing([
            _local,
            _local.User
        ]);
    
    
        _local.User.user = "newUser"; //Trying to assing new value
    
        //Remain with the same value as first declaration
        console.log(_local.User.user); //--> "1stUser"           
        return $r;
    })("config");
    

提交回复
热议问题