【问题标题】:prevent changing value of a property in Javascript prototype object防止更改 Javascript 原型对象中的属性值
【发布时间】:2017-05-25 12:56:31
【问题描述】:

我有一个对象,其中我有一个名为“国家”的属性,即爱尔兰。我想阻止开发人员在尝试在代码级别更新时更新属性。有没有机会做呢?如果有,请告诉我

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

            },
            country: "Ireland",


        }

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

我不希望将国家/地区设置为爱尔兰以外的任何其他值。我可以通过检查 if 条件来做到这一点。除了 if 条件,我还有其他方法吗?

【问题讨论】:

标签: javascript prototype


【解决方案1】:

一种可能的方法是在init()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',
};

这种方法有一个非常有趣的特性:您可以通过原型调整属性,这将影响从那时起创建的所有对象:

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 变成init 函数的私有变量,如下所示:

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

【讨论】:

  • 完美。但这意味着什么可配置:false,可写:false?
  • 首先意味着不能更改属性描述符(例如,将其恢复为可写)或删除它,其次 - 不能通过赋值更改值。查看Object.defineProperty() 的文档了解更多详情。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多