防止在Javascript原型对象中更改属性的值

问题描述:

我有一个对象,我有一个名为“country”的属性作为Ireland。我想阻止开发人员在尝试更新代码级别时更新属性。有没有这样做的机会?如果是这样,请让我知道防止在Javascript原型对象中更改属性的值

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

      }, 
      country: "Ireland", 


     } 

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

我不希望国家被设置为除爱尔兰以外的任何其他值。我可以通过检查条件来做到这一点。而不是如果条件,我可以有任何其他方式吗?

+1

的可能的复制[?如何创建JavaScript常量使用const关键字对象的属性(https://*.com/questions/10843572/how-to-create-javascript -constants-as-properties-of-objects-using-const-keyword) –

一个可能的方法与Object.defineProperty()定义在init()这个属性为不可写:

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

这种方法有一个非常有趣的功能:您可以通过调整原型财产,而且会影响到所有的对象从那时起创建:

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 

如果你不希望这样的事情发生,无论是防止Car.prototype修改,或将country成私有变量功能,像这样:

Car.prototype = { 
    init: function() { 
    var country = 'Ireland'; 
    Object.defineProperty(this, 'country', { 
     value: country, 
    }); 
    } 
}; 
+0

完美。但是这意味着什么可配置:false, 可写:false? –

+0

首先表示不能更改属性描述符(例如将其重新写入可写)或删除它,其次 - 不能通过赋值更改值。查看Object.defineProperty()的文档以获取更多细节。 – raina77ow