0

I'm having a object where I've one property called "country" as Ireland. I want to prevent the developer to update the property when he tries to update in the code level. Is there any chance of doing it? If so, please let me know

var Car = function() {
            this.init();
            return this;
        }
        Car.prototype = {
            init : function() {

            },
            country: "Ireland",


        }

        var c = new Car();
        c.country = 'England';

I dont want country to be set to any other value other than Ireland. I can do this by checking with if condition. Instead of if conditions, can I have any other way?

raina77ow
  • 103,633
  • 15
  • 192
  • 229
Syed Sha
  • 151
  • 2
  • 12
  • 1
    Possible duplicate of [How to create Javascript constants as properties of objects using const keyword?](https://stackoverflow.com/questions/10843572/how-to-create-javascript-constants-as-properties-of-objects-using-const-keyword) – Pablo Lozano May 25 '17 at 13:12

1 Answers1

2

One possible approach is defining this property as non-writable in init() with Object.defineProperty():

Car.prototype = {
  init: function() {
    Object.defineProperty(this, 'country', {
      value: this.country,
      enumerable: true, // false if you don't want seeing `country` in `for..of` and other iterations
      /* set by default, might want to specify this explicitly 
      configurable: false,
      writable: false
      */
    });
  },
  country: 'Ireland',
};

This approach has one very interesting feature: you can adjust property via prototype, and that'll affect all the objects created since then:

var c1 = new Car();
c1.country = 'England';
console.log(c1.country); // Ireland
c1.__proto__.country = 'England'; 
console.log(c1.country); // Ireland
var c2 = new Car();
console.log(c2.country); // England

If you don't want this to happen, either prevent modification of Car.prototype, or turn country into a private variable of init function, like this:

Car.prototype = {
  init: function() {
    var country = 'Ireland'; 
    Object.defineProperty(this, 'country', {
      value: country,
    });
  }
};
raina77ow
  • 103,633
  • 15
  • 192
  • 229
  • Perfect. But what does this mean configurable: false, writable: false? – Syed Sha May 25 '17 at 13:25
  • First means one cannot change a property descriptor (turn it back into writable, for example) or delete it, second - one cannot change value via assignment. Check the docs of `Object.defineProperty()` for more details. – raina77ow May 25 '17 at 13:27