[英]prevent changing value of a property in Javascript prototype object
我有一個對象,其中有一個名為“國家”的財產,例如愛爾蘭。 我想防止開發人員在嘗試在代碼級別進行更新時更新屬性。 有這樣做的機會嗎? 如果是這樣,請告訴我
var Car = function() {
this.init();
return this;
}
Car.prototype = {
init : function() {
},
country: "Ireland",
}
var c = new Car();
c.country = 'England';
我不希望將國家/地區設置為愛爾蘭以外的任何其他值。 我可以通過檢查if條件來做到這一點。 除了條件以外,我還有其他方法嗎?
一種可能的方法是使用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
變成init
函數的私有變量,如下所示:
Car.prototype = {
init: function() {
var country = 'Ireland';
Object.defineProperty(this, 'country', {
value: country,
});
}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.