Is there any way to prevent replacement of JavaScript object properties?

后端 未结 6 1937
醉酒成梦
醉酒成梦 2020-12-16 00:21

I would like to make an object\'s structure immutable, preventing its properties from being subsequently replaced. The properties need to be readable, however. Is this possi

6条回答
  •  半阙折子戏
    2020-12-16 01:17

    the best thing you can do is hide your properties inside of a closure.

    var getMap = function(){
      var hidden = "1";
      return {
        getHidden : function() { return hidden; }
      }
    }
    
    var f = getMap ();
    
    alert(f.getHidden());
    

    I took a stab at it. In the above code you will need to not just return hidden but copy it into a new object perhaps. maybe you can use jquery's extend to do this for you, so you will be returning a new object, not the reference. This may be completely wrong though =)

提交回复
热议问题