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

后端 未结 6 1926
醉酒成梦
醉酒成梦 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:04

    Okay, so there's been already a couple of answers suggesting you return an object with several getters methods. But you can still replace those methods.

    There's this, which is slightly better. You won't be able to replace the object's properties without replacing the function completely. But it's still not exactly what you want.

    function Sealed(obj) {
        function copy(o){
            var n = {}; 
            for(p in o){
                n[p] = o[p]
            }
            return n;
        }
        var priv = copy(obj);
        return function(p) {
            return typeof p == 'undefined' ? copy(priv) : priv[p];  // or maybe copy(priv[p])
        }
    }
    
    var mycar = new Sealed({make:"ford", model:"mustang", color:"black"});
    
    alert( mycar('make') ); // "ford"
    alert( mycar().make );  // "ford"
    
    var newcopy = mycar();
    newcopy.make = 'volkwagen';
    alert( newcopy.make ); // "volkwagen"  :(
    
    alert( mycar().make );   // still "ford"  :)
    alert( mycar('make') );   // still "ford" :)
    

提交回复
热议问题