Syed Sha
Syed Sha

Reputation: 151

prevent changing value of a property in Javascript prototype object

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?

Upvotes: 0

Views: 2570

Answers (1)

raina77ow
raina77ow

Reputation: 106395

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,
    });
  }
};

Upvotes: 2

Related Questions