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

后端 未结 6 1929
醉酒成梦
醉酒成梦 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条回答
  •  Happy的楠姐
    2020-12-16 01:21

    As mkoryak said, you can create a closure to hide properties

    function Car(make, model, color) {
        var _make = make, _model = model, _color = color; 
    
        this.getMake = function() {
            return _make;
        }
    
    }
    
    var mycar = new Car("ford", "mustang", "black");
    
    mycar.getMake(); //returns "ford"
    mycar._make; //error
    

提交回复
热议问题