2017-05-25 58 views
0

我有一個對象,我有一個名爲「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://stackoverflow.com/questions/10843572/how-to-create-javascript -constants-as-properties-of-objects-using-const-keyword) –

回答

2

一個可能的方法與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